4

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

1 2 3 4

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

4

2 回答 2

8

两种可能的解决方案是:

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

伪代码:

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)时间解决方案是对两个数组进行排序,然后迭代并检查它们是否相同。

于 2012-09-04T06:16:09.827 回答
0

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

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;
}
于 2019-10-31T00:58:40.583 回答