Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
O(n log n)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (empty(nums)) {
return 0;
}
sort(begin(nums), end(nums));
nums.erase(unique(begin(nums), end(nums)), end(nums));
int res = 1;
vector<int> dp(size(nums), 1);
for (int i = 1; i < size(nums); ++i) {
if (nums[i] == nums[i - 1] + 1) {
dp[i] = dp[i - 1] + 1;
}
res = max(res, dp[i]);
}
return res;
}
};
O(n)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(begin(nums), end(nums));
int res = 0;
for (auto& x : nums) {
if (!s.count(x - 1)) {
int cnt = 1;
while (s.count(x + cnt)) {
++cnt;
}
res = max(res, cnt);
}
}
return res;
}
};