问题描述:
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
解题思路:
这道题是道easy,但是我错了很多次,都是因为粗心。
第一次没有读明白题,以为abs(i-j) == k。错了
后面写码用了O(n2)的方法,多次出错:比如i j 搞混了
可以用hashmap存储int 和 它的index。
是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.count(nums[i]) != 0){ if(i - m[nums[i]] <= k) return true; } m[nums[i]] = i; } return false; } };