|
4 | 4 | */
|
5 | 5 | const containsDuplicate = (nums) => {
|
6 | 6 | // nums = [1, 2, 3, 1]
|
7 |
| - let isDuplicated = false, l = 0, r = nums.length - 1; |
| 7 | + let map = {}, l = 0, r = nums.length - 1; |
| 8 | + // const map = new Map(nums.map((value, index) => [value, index])); |
| 9 | + // console.log(map) |
8 | 10 |
|
9 |
| - // for |
10 |
| - // think about other edge cases ... |
11 |
| - // for (let i = 0; i < nums.length; i++) { |
12 |
| - // if (l == r) { |
13 |
| - // |
14 |
| - // } |
15 |
| - |
16 |
| - while (r >= l) { |
17 |
| - if (l === r) { |
18 |
| - l++; |
19 |
| - r = nums.length - 1; |
| 11 | + for (let i = 0; i < nums.length; i++) { |
| 12 | + if (undefined === map[nums[i]]) { |
| 13 | + map[nums[i]] = i; |
20 | 14 | continue;
|
21 | 15 | }
|
22 | 16 |
|
23 |
| - if (nums[l] === nums[r]) { |
24 |
| - isDuplicated = true; |
25 |
| - break; |
26 |
| - } else { |
27 |
| - r--; |
28 |
| - } |
| 17 | + return true; |
29 | 18 | }
|
| 19 | + console.log("??") |
| 20 | + console.log(map) |
30 | 21 |
|
31 |
| - return isDuplicated; |
| 22 | + return false; |
32 | 23 | }
|
33 | 24 |
|
34 |
| -containsDuplicate([1, 2, 3, 1]) |
| 25 | +// containsDuplicate([1, 2, 3, 1]) |
35 | 26 | containsDuplicate([1, 2, 3, 4])
|
36 |
| -containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) |
| 27 | +// containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) |
37 | 28 | // containsDuplicate()
|
| 29 | + |
| 30 | +// 2 pointer solution |
| 31 | +// const containsDuplicate = (nums) => { |
| 32 | +// // nums = [1, 2, 3, 1] |
| 33 | +// let isDuplicated = false, l = 0, r = nums.length - 1; |
| 34 | +// const map = new Map(nums.map((value, index) => [value, index])); |
| 35 | +// console.log(map) |
| 36 | +// |
| 37 | +// // for |
| 38 | +// // think about other edge cases ... |
| 39 | +// // for (let i = 0; i < nums.length; i++) { |
| 40 | +// // if (l == r) { |
| 41 | +// // |
| 42 | +// // } |
| 43 | +// |
| 44 | +// while (r >= l) { |
| 45 | +// if (l === r) { |
| 46 | +// l++; |
| 47 | +// r = nums.length - 1; |
| 48 | +// continue; |
| 49 | +// } |
| 50 | +// |
| 51 | +// if (nums[l] === nums[r]) { |
| 52 | +// isDuplicated = true; |
| 53 | +// break; |
| 54 | +// } else { |
| 55 | +// r--; |
| 56 | +// } |
| 57 | +// } |
| 58 | +// |
| 59 | +// return isDuplicated; |
| 60 | +// } |
0 commit comments