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 boolean containsNearbyDuplicate(int[] nums, int k) { boolean result = false; for(int i = 0; i < nums.length - 1; i++){ for(int j = i+1; j < nums.length; j++){ if((nums[i]==nums[j]) && Math.abs(i - j) <= k) result = true; } } return result; } }
1。 懒人方法,双重循环
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { // boolean result = false; // for(int i = 0; i < nums.length - 1; i++){ // for(int j = i+1; j < nums.length; j++){ // if((nums[i]==nums[j]) && Math.abs(i - j) <= k) result = true; // } // } // return result;
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (hashMap.containsKey(nums[i]) && i - hashMap.get(nums[i]) <= k) {
return true;
}
hashMap.put(nums[i], i);
}
return false;
}
}
方法2:用hashmap来读和存数,遇到相同的计算一下距离。注意题目是只要存在有两个相同的,而且index之差小于等于k即可,一经成立就可以返回true。