| 1 | // time O(n) |
| 2 | // space O(n) |
| 3 | function largestRange(array) { |
| 4 | const dic = {}; |
| 5 | let bestRange = []; |
| 6 | let longesLenght = 0; |
| 7 | |
| 8 | for (const num of array) { |
| 9 | dic[num] = true; |
| 10 | } |
| 11 | |
| 12 | for (const num of array) { |
| 13 | if (!dic[num]) continue; |
| 14 | dic[num] = false; |
| 15 | let currentLenght = 1; |
| 16 | let left = num - 1; |
| 17 | let right = num + 1; |
| 18 | while (left in dic) { |
| 19 | dic[left] = false; |
| 20 | currentLenght++; |
| 21 | left--; |
| 22 | } |
| 23 | while (right in dic) { |
| 24 | dic[right] = false; |
| 25 | currentLenght++; |
| 26 | right++; |
| 27 | } |
| 28 | if (currentLenght > longesLenght) { |
| 29 | longesLenght = currentLenght; |
| 30 | bestRange = [left + 1, right - 1]; |
| 31 | } |
| 32 | } |
| 33 | return bestRange; |
| 34 | } |
| 35 | |
| 36 | const array = [1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6]; |
| 37 | |