Given an array of integers and an integer
k
, find out whether there 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
.
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
class
Solution {
public
boolean
containsNearbyDuplicate(
int
[] nums,
int
k) {
if
(k<
0
){
return
false
;
}
//通过HashMap来比较是否有重复值
HashMap numsToHashMap =
new
HashMap();
for
(
int
n=
0
;n<nums.length;n++){
//如果有重复值且重复值索引之间的差值不大于k,则返回true
if
(numsToHashMap.containsKey(nums[n])&&(n-(
int
)numsToHashMap.get(nums[n])<=k)){
return
true
;
}
//否则,则将该值以及其索引存入HashMap
numsToHashMap.put(nums[n],n);
}
return
false
;
}
}
|
Given an array of integers and an integer
k
, find out whether there 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
.
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
class
Solution {
public
boolean
containsNearbyDuplicate(
int
[] nums,
int
k) {
if
(k<
0
){
return
false
;
}
//通过HashMap来比较是否有重复值
HashMap numsToHashMap =
new
HashMap();
for
(
int
n=
0
;n<nums.length;n++){
//如果有重复值且重复值索引之间的差值不大于k,则返回true
if
(numsToHashMap.containsKey(nums[n])&&(n-(
int
)numsToHashMap.get(nums[n])<=k)){
return
true
;
}
//否则,则将该值以及其索引存入HashMap
numsToHashMap.put(nums[n],n);
}
return
false
;
}
}
|