【问题标题】:Detect a permutation of sequence检测序列的排列
【发布时间】:2012-09-04 06:14:06
【问题描述】:

我有一个这样的数字列表(数组)

1 2 3 4

所以我的目标是检查给定另一个数组,如果这个数组是原始示例的排列,数组(3 4 1 2)(1 2 4 3) 是原始排列,但(1 2 1 1)(1 5 4 3) 不是。

【问题讨论】:

    标签: arrays algorithm language-agnostic permutation


    【解决方案1】:

    两种可能的解决方案是:

    (1) O(n) 空间和平均时间解决方案将基于哈希表创建数据的histogram - 并检查直方图是否相同。这个想法是 - 计算每个元素在每个列表中出现的次数,然后检查每个元素在每个数组中出现的次数完全相同

    伪代码:

    map1 = new map //first histogram
    map2 = new map //second histogram
    for each element in arr1: //create first histogram
       if (element in map1):
             map1.put(element,map1.get(element)+1)
       else:
             map1.put(element,1)
    for each element in arr2: //create second histogram
       if (element in map2):
             map2.put(element,map2.get(element)+1)
       else:
             map2.put(element,1)
    for each key in map 1: //check all elements in arr1 appear in arr2
       if map1.get(key) != map2.get(key):
            return false
    //make sure the sizes also match, it means that each element in arr2 appears in arr1.
    return arr1.length == arr2.length 
    

    (2) O(nlogn) 时间解决方案是对两个数组进行排序,然后迭代并检查它们是否相同。

    【讨论】:

    • 你能解释一下第一个替代方案吗?
    • @eli.rodriguez:替代方案是基于直方图的解决方案?我添加了一个伪代码
    • 您用 Python 实现的直方图伪代码:from collections import Counter; return Counter(arr1) == Counter(arr2)。 :)
    • @Dougal:谢谢。因为它不是 python 特定的问题——我认为向 OP 展示它的实际运行情况是件好事(我相信,python 代码将被翻译成与此非常相似的东西)。但是,是的,它向我们展示了高级语言相对于低级语言的简单性。
    【解决方案2】:

    如果你确定有一个序列,你可以检查给定数组的排列是否更快。 只需计算序列中所有元素的总和,并将其与给定数组中的元素总和进行比较。

    bool is_permutation(vector<int> &v, vector<int> &s) {
        // size of the sequence
        int v_size = v.size();
        // size of probable permutation.
        int s_size = s.size();
        // Calculate a sum of all elements of the sequence
        int sum_of_sequence = (v_size * (1 + v_size)) / 2;
        // Count actual sum of elements
        int sum_of_all_elements = std::accumulate(v.begin(), v.end(), 0);
        // If the sums are equal the array contains a permuted sequence
        return sum_of_sequence == sum_of_all_elements;
    }
    

    【讨论】:

    • 但是,相同长度的序列不能彼此不是排列产生相同的总和吗?例如。 5 7 9 110 1 2 29。您需要做的是检查两件事:0)两个序列的长度相同,1)序列A 的每个元素在序列B 中只出现一次(反之亦然)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2021-11-09
    • 2019-06-04
    • 1970-01-01
    相关资源
    最近更新 更多