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
题目不难,肯定是用map,记录重复值,并比较器index,第一个本能算法,把所有相同的数字的index都保存了,对是对,效率低。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, vector<int>> helper;
for(int i = 0; i < nums.size(); i++)
{
if(helper.count(nums[i]) > 0)
{
for(auto item : helper[nums[i]])
{
if(abs(item - i) <= k)
return true;
}
helper[nums[i]].push_back(i);
}
else
helper[nums[i]].push_back(i);
}
return false;
}
};
后来看别人的答案,才发现,在遍历的过程中,只要保存最近的一个相同数字的index即可,因为远的那个距离更大,所以,有如下算法。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> helper;
for(int i = 0; i < nums.size(); i++)
{
if(helper.count(nums[i]) > 0)
{
if(abs(helper[nums[i]] - i) <= k)
return true;
helper[nums[i]] = i;
}
else
helper[nums[i]] = i;
}
return false;
}
};
Runtime: 48 ms, faster than 79.60% of C++ online submissions for Contains Duplicate II.
Memory Usage: 16.6 MB, less than 30.40% of C++ online submissions for Contains Duplicate II.
上面用了unordered_map,本来对这两种map并没有可以区分,不过针对这个题目倒是有点好奇,所以换了一下,结果还是有明显差异的,无论查找速度还是内存。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> helper;
for(int i = 0; i < nums.size(); i++)
{
if(helper.count(nums[i]) > 0)
{
if(abs(helper[nums[i]] - i) <= k)
return true;
helper[nums[i]] = i;
}
else
helper[nums[i]] = i;
}
return false;
}
};
Runtime: 84 ms, faster than 26.90% of C++ online submissions for Contains Duplicate II.
Memory Usage: 17.1 MB, less than 20.81% of C++ online submissions for Contains Duplicate II.