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.
解法一
这道题不算难题,就是使用一个哈希表,遍历整个数组,如果哈希表里存在,返回false,如果不存在,则将其放入哈希表中,代码如下:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
//find()如果找到返回下标,未找到则返回最后一个元素的下标
if (m.find(nums[i]) != m.end()) return true;
++m[nums[i]];
}
return false;
}
};
这题还有另一种解法,就是先将数组排个序,然后再比较相邻两个数字是否相等,时间复杂度取决于排序方法,代码如下:
解法二
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i - 1]) return true;
}
return false;
}
};
参考:http://www.cnblogs.com/grandyang/p/4537029.html
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
在上面的基础上找到数组是否有重复的数,同时重复数的下标间隔不超过k。
解法一:
同样适用unorder_map来解决这个问题,如果map里面已经有了这个数就比较下标,如果符合要求返回true;如果不符合要求则更新该数的下标。
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (nums.size() <= 1){
return false;
}
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); i++){
if (m.find(nums[i]) != m.end() && m[nums[i]] >= i - k){
return true;
}
m[nums[i]] = i;
}
return false;
}
解法二:
使用set来实现。
bool containsNearbyDuplicate(vector<int>& nums, int k) {
// the set only record k (or less than k) numbers before nums[i]
set<int> st;
for (int i = 0; i < nums.size(); ++i) {
if (st.find(nums[i]) != st.end()) {
return true;
}
if (st.size() < k) {
st.insert(nums[i]);
} else {
// insert first, or wrong when k=0
st.insert(nums[i]);
st.erase(nums[i - k]);
}
}
return false;
}
参考:https://github.com/illuz/leetcode/tree/master/solutions/219.Contains_Duplicate_II