|
6 | 6 | - N = Number of elements in array |
7 | 7 |
|
8 | 8 | The most intuitive solution is to sort the array, then iterate each number to find the longest range. |
9 | | -Hoever, that would be N(log(N)) run-time. |
| 9 | +However, that would be N(log(N)) run-time. |
10 | 10 |
|
11 | 11 | To improve the run-time, we can store all the numbers into a set, then check if the left(n-1) and right(n+1) numbers are in the set. |
12 | | -However, the run-time would be poor(O(N^2)), you would need a visited set to avoid traversing left and right for each number in the set to get O(N). |
| 12 | +However, the run-time would be poor, O(N^2), you would need a visited set to avoid traversing left and right for each number in the set to get O(N). |
13 | 13 |
|
14 | 14 | You can further improve the space complexity by only starting at either the left-most number or the right-most number. |
15 | 15 | That would mean you just traverse only in one direction, avoiding the need of a visited set. |
16 | 16 |
|
17 | 17 | ``` |
18 | 18 | class Solution: |
19 | 19 | def longestConsecutive(self, nums: List[int]) -> int: |
20 | | - if len(nums) == 0: |
21 | | - return 0 |
22 | | - num_set = set(nums) |
23 | | - longest_range = 0 |
24 | | - for n in num_set: |
25 | | - if n-1 not in num_set: # beginning of a range |
26 | | - curr_n = n |
27 | | - while curr_n+1 in num_set: |
28 | | - curr_n += 1 |
29 | | - longest_range = max(longest_range, curr_n-n) |
30 | | - return longest_range+1 |
| 20 | + num_set, longest_length = set(nums), 0 |
| 21 | + for n in nums: |
| 22 | + if n-1 not in num_set: # left-most number |
| 23 | + length, curr = 0, n |
| 24 | + while curr in num_set: |
| 25 | + curr, length = curr+1, length+1 |
| 26 | + longest_length = max(longest_length, length) |
| 27 | + return longest_length |
31 | 28 | ``` |
0 commit comments