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 absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
我的第一反应解法:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, vector<int>> nums_map;
for (int i=0; i<nums.size(); ++i) {
nums_map[nums[i]].push_back(i);
}
for (auto& m : nums_map) {
sort(m.second.begin(), m.second.end());
for (int i=1; i<m.second.size(); ++i) {
if (m.second[i]-m.second[i-1] <= k) return true;
}
}
return false;
}
};
Runtime: 72 ms, faster than 30.66% of C++ online submissions for Contains Duplicate II.
Memory Usage: 21.4 MB, less than 6.84% of C++ online submissions for Contains Duplicate II.
笔记:
https://stackoverflow.com/questions/25195233/time-complexity-of-iterating-through-a-c-unordered-map
遍历unordered map是O(n)
上面这个方法是O(nlogn)
下面这个来自评论区O(n)
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> m;
for(int i=0; i<nums.size();i++){
if(m.find(nums[i]) == m.end()) m[nums[i]] =i;
else {
if (i - m[nums[i]] <= k) return true;
else m[nums[i]] = i;
}
}
return false;
}
};
其实不需要找所有的,只需要每个数字记住上一个出现的index就行了
网友评论