|
| 1 | +// Time: O(n) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int longestConsecutive(vector<int>& nums) { |
| 7 | + // unprocessed_entries records the existence of each entry in num. |
| 8 | + unordered_set<int> unprocessed_entries; |
| 9 | + for (const auto& num : nums) { |
| 10 | + unprocessed_entries.emplace(num); |
| 11 | + } |
| 12 | + |
| 13 | + int max_interval_size = 0; |
| 14 | + while (!unprocessed_entries.empty()) { |
| 15 | + int num = *unprocessed_entries.begin(); |
| 16 | + unprocessed_entries.erase(num); |
| 17 | + |
| 18 | + // Finds the lower bound of the largest range containing a. |
| 19 | + int lower_bound = num - 1; |
| 20 | + while (unprocessed_entries.count(lower_bound)) { |
| 21 | + unprocessed_entries.erase(lower_bound); |
| 22 | + --lower_bound; |
| 23 | + } |
| 24 | + |
| 25 | + // Finds the upper bound of the largest range containing a. |
| 26 | + int upper_bound = num + 1; |
| 27 | + while (unprocessed_entries.count(upper_bound)) { |
| 28 | + unprocessed_entries.erase(upper_bound); |
| 29 | + ++upper_bound; |
| 30 | + } |
| 31 | + max_interval_size = |
| 32 | + max(max_interval_size, upper_bound - lower_bound - 1); |
| 33 | + } |
| 34 | + return max_interval_size; |
| 35 | + } |
| 36 | +}; |
| 37 | + |
| 38 | +// Time: O(n) |
| 39 | +// Space: O(n) |
| 40 | +class Solution2 { |
| 41 | +public: |
| 42 | + int longestConsecutive(vector<int> &nums) { |
| 43 | + if (nums.empty()) { |
| 44 | + return 0; |
| 45 | + } |
| 46 | + unordered_map<int, int> hash; |
| 47 | + int ans{1}; |
| 48 | + for (const auto& i : nums) { |
| 49 | + if (!hash[i]) { |
| 50 | + hash[i] = 1; |
| 51 | + int leftbound{hash[i - 1]}, rightbound{hash[i + 1]}; // Get neighbor info. |
| 52 | + hash[i - leftbound] = hash[i + rightbound] = 1 + leftbound + rightbound; // Update left and right bound info. |
| 53 | + ans = max(ans, 1 + leftbound + rightbound); |
| 54 | + } |
| 55 | + } |
| 56 | + return ans; |
| 57 | + } |
| 58 | +}; |
0 commit comments