列表中具有重复项和位置的唯一对
Unique pairs in list with duplicates & position
在准备技术面试时,我的一个朋友遇到了一个有趣的问题:给定一个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]}
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 何时在引用或唯一指针上使用移动语义
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 计算排序向量的向量中唯一值的计数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 通过组合不同的类型来创建唯一的id
- 使用Unique_ptr确保工厂中的对象唯一
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 每5、10和最后一个位置打印唯一的字符串
- 我想得到一组唯一的n*n数组,这些数组在c++中的随机位置只包括0或1