forked from lilins/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp219.js
More file actions
32 lines (29 loc) · 845 Bytes
/
p219.js
File metadata and controls
32 lines (29 loc) · 845 Bytes
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
27
28
29
30
31
32
/**
* 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.
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var containsNearbyDuplicate = function(nums, k) {
let count = []
let index = 0
for(let item of nums){
count[item] ? count[item].push(index) : count[item] = [index]
let result = count[item].length >= 2
? count[item][count[item].length-1] - count[item][count[item].length-2]
: k+1
if(result <= k) return true
index ++
}
console.log(count)
return false
};
/**
* 在这里,可以不保存所有出现的值,只需要保留上一个值即可。
*/
console.log(containsNearbyDuplicate([1,2,3,4,5,1,1],2))