Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
本题虽然简单, 看下老外的总结: This problem is trivial but quite nice example of space-time tradeoff.
直接想到的是用set<int> set
:
扫数组, 问是否在set中找到,若有, 则返回 false
;
若未找到, 将该元素入set;
若顺利扫完数组, 返回 true
;
学习set声明和简单用法:
set<int> set;
set.insert(A[i]);
//表找到元素, set.end()表最后一个元素后面的位置
//find()若找到, 返索引, 否则返回最后一个元素后面的位置
set.find(A[i]) != set.end() //表找到
方法1: 简单的双重循环, (O(n^2)) time, (O(1)) extra space.
方法2: 先排序,再线性查找, (O(nlogn)) time, (O(1)) extra space.
bool containsDuplicate(vector<int>& A) {
int n = A.size();
if (n == 0 || n == 1) return false;
sort(A.begin(), A.end()); // 注意: vector中sort的应用
for (int i = 1; i < n; i++) {
if (A[i] == A[i - 1]) return true;
}
return false;
}
方法3: 用set, 想用hash_set,可能更快. (O(n)) time, (O(n)) extra space.
//用set
bool containsDuplicate(vector<int>& A) {
int n = A.size();
set<int> set;
for (int i = 0; i < n; i++) {//注意下面如何表示找到
if (set.find(A[i]) != set.end()) return true;
set.insert(A[i]);
}
return false;
}