哈希表
Problem:
思路
先开用的暴力,结果有个样例超时了,然后改用哈希表
Code
暴力枚举
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int n = nums.length;
boolean res = false;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n && j <= i + k; j++) {
if (nums[i] == nums[j] && Math.abs(i - j) <= k) {
res = true;
}
}
}
return res;
}
}
哈希表
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int length = nums.length;
for (int i = 0; i < length; i++) {
int num = nums[i];
if (map.containsKey(num) && i - map.get(num) <= k) {
return true;
}
map.put(num, i);
}
return false;
}
}