题目:
Given an array of integers and an integer k, find out whether there are two distinct indices iand j in the array such that nums[i] = nums[j] and the difference between i and j is at mostk.
思路:
比较常规的题,将元素做为键,元素位置作为值,添加到map中。
遇到合适的值则直接返回true,一直没有就返回false。(如果将if判断拆开则效率降低。注意一下)
代码:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> m;
for(int i = 0; i < nums.size(); i++){
if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) return true;
else m[nums[i]] = i;
}
return false;
}