219. Contains Duplicate II
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 difference between i and j is at most k.
大概意思就是一个整数数组,和一个整数k,数组中有两个下标不同 i 和j ,但是值却相同nums[i]=nums[j];i 和 j 之间的差小于等于k。
如果存在这样的两个元素返回true。如果不存在返回false
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
if (map.size() < i+1) {//map集合元素个数小于存入的个数,说明有重复值
for (int j = 0; j < i; j++) {//遍历重复值之前的数组,找到下标
if (nums[j] == nums[i]) {
if (i-j <= k) {//比较两个相同元素的下标与k的大小关系
return true;
}
}
}
}
}
return false;
}
}