首页>itarticle>【leetcode】 219. contains duplicate ii
【leetcode】 219. contains duplicate ii
admin11月 13, 20200
Description
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.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
publicboolean(int[] nums, int k){
Map<Integer, List<Integer>> map = new HashMap<>();
int len = nums.length;
if (len == 0 || k == 0) {
returnfalse;
}
for (int i = 0; i < len; i++) {
List<Integer> l = new ArrayList<>();
if (map.containsKey(nums[i])) {
l = map.get(nums[i]);
}
l.add(i);
map.put(nums[i], l);
}
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
近期评论