c++ - 列表中具有重复项和位置的唯一对

标签 c++ algorithm data-structures big-o

在准备技术面试时,我的一个 friend 遇到了一个有趣的问题:给定一个包含 n 个整数的列表,找到所有相同的对并返回它们的位置。

Example  input:  [3,6,6,6,1,3,1]  
Expected output: (0,5), (1,2), (1,3), (2,3), (4,6)

Stack Overflow 有大量关于唯一对的存在性检查或特殊情况(如无重复)的答案,但我没有找到通用、快速的解决方案。我下面的方法的时间复杂度是 O(n) 最好的情况,但降级到 O(n^2) 最坏的情况(输入值都相同)。

有没有办法将其降低到 O(n*logN) 最坏情况?

// output is a vector of pairs
using TVecPairs= vector<pair<size_t,size_t>>;

TVecPairs findPairs2( const vector<uint32_t> &input ) 
{
    // map keyvalue -> vector of indices
    unordered_map<uint32_t, vector<size_t>> mapBuckets;

    // stick into groups of same value
    for (size_t idx= 0; idx<input.size(); ++idx) {
        // append index for given key value
        mapBuckets[input[idx]].emplace_back( idx );
    }

    // list of index pairs
    TVecPairs out;

    // foreach group of same value
    for (const auto &kvp : mapBuckets) { 
        const vector<size_t> &group= kvp.second;
        for (auto itor= cbegin(group); itor!=cend(group); ++itor) {
            for (auto other= itor+1; other!=cend(group); ++other) {
                out.emplace_back( make_pair(*itor,*other) );
            }
        }
    }
    return out;
}

最佳答案

正如其他人所说,它是一个 O(n^2),以防您想要以您提到的方式输出。如果你可以用不同的方式打印它,你可以在 C++ 中用 O(n * (插入/从 hashmap 读取的复杂性) = O(n*log(n)) 来实现。描述上述内容的一些 python 代码如下:

def dupes(arrlist):
   mydict=dict()
   count = 0
   for x in arrlist:
      if mydict.has_key(x):
         mydict[x] = mydict[x] + [count]
      else:
         mydict[x] = [count]
      count = count + 1
   print mydict
   return

对于上面的例子:

>>> dupes([3, 6, 6, 6, 1, 3, 1])
{1: [4, 6], 3: [0, 5], 6: [1, 2, 3]}

关于c++ - 列表中具有重复项和位置的唯一对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31364456/

相关文章:

database - 如果是社交网站,数据将如何存储在数据库中?

algorithm - 流数据和识别主题的数据结构/算法

perl - Perl : an array of hash references or list of "flat" hashes? 中什么更好

c++ - C++ 中 openMP Shared 子句的用法

c++ - 在QT中显示代码输出到主窗口

c++ - SDL_image 不工作

java - 矩形可挠度的最小周长

c++ - Qt4 : Decorating a QLineEdit (painting around it)

javascript - 洪水填充算法选择具有最少邻居数的像素

algorithm - 在列表中查找最低未使用的唯一 ID