-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path219. COntains Duplicate II.js
107 lines (96 loc) · 2.58 KB
/
219. COntains Duplicate II.js
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
*/
/**
* Note:
* 1. Hash Map(value, index)
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var containsNearbyDuplicate = function(nums, k) {
if (nums === null || nums.length === 0) {
return false;
}
let map = new Map();
for (let i = 0; i < nums.length; i++) {
if (map.has(nums[i])) {
if (i - map.get(nums[i]) <= k) {
return true;
} else {
map.set(nums[i], i);
}
} else {
map.set(nums[i], i);
}
}
return false;
};
/**
* Leetcode Fundamental: 11/8 Update
*
* Declare a map with key: nums[bound], value: bound (current end becomes start for next round)
* for (let bound = 0; bound < nums.length; bound += 1)
* Timing:
* if (nums[end] === nums[start])
* if (end - start <= k): return true;
* else: update end to lastest bound
* else:
* update end to latest bound
*
* Fail to find the timing to update map
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var containsNearbyDuplicate = function(nums, k) {
if (nums === undefined || nums.length === 0) return false;
let map = new Map();
for (let bound = 0; bound < nums.length; bound += 1) {
if (map.has(nums[bound])) {
if (bound - map.get(nums[bound]) <= k) {
return true;
} else {
map.set(nums[bound], bound);
}
} else {
map.set(nums[bound], bound);
}
}
return false;
};
/**
* 玩轉算法 11/8 Update
* 1. The question can be transformed into finding an interval of length k and check if there
* are pairs nums[start], nums[end] where nums[start] === nums[end]
*
* 2. Maintain a set of nums[i] with length <= k (contains nums[l...l+k])
* a. check if next nums[l+k+1] is in set: return true
* b. else: set.add(nums[l+k+1])
* if (set.size > k) set.delete(nums[l]) (l = i-k)
* 3. No valid pairs found: return false
*
* Store valid elements in set, maintain interval by maintaining the set
*/
const containsNearbyDuplicate = (nums, k) => {
if (nums === undefined || nums.length === 0) return false;
let set = new Set();
for (let bound = 0; bound < nums.length; bound += 1) {
if (set.has(nums[bound])) return true;
set.add(nums[bound]);
if (set.size > k) set.delete(nums[bound-k]);
}
return false;
};