
复杂度分析
时间复杂度:O(n),其中 n 为数组的长度。
空间复杂度:O(n)。哈希表存储数组中所有的数需要 O(n) 的空间。
链接:力扣
题解:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
std::unordered_set<int> table(nums.begin(), nums.end());
int length = 0;
while (!table.empty()) {
int val = *(table.begin());
table.erase(val);
int pre = val-1;
int l = 1;
while (table.find(pre) != table.end()) {
++l;
table.erase(pre);
--pre;
}
int next = val+1;
while (table.find(next) != table.end()) {
++l;
table.erase(next);
++next;
}
length = max(length, l);
}
return length;
}
};
class Solution {
public:
/**
* @param nums: A list of integers
* @return an integer
*/
int longestConsecutive(vector<int> &num) {
// write you code here
unordered_set<int> map(num.begin(), num.end());
int ans = 0;
for (int i = 0; i < num.size(); i++) {
if (map.find(num[i]) != map.end()) {
map.erase(num[i]);
int pre = num[i] - 1;
int next = num[i] + 1;
while (map.find(pre) != map.end()) {
map.erase(pre);
pre--;
}
while (map.find(next) != map.end()) {
map.erase(next);
next++;
}
ans = max(ans, next - pre - 1);
}
}
return ans;
}
};
(1)unordered_map存储存在的元素
(2)以begin为序列开头,的序列的最大长度
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.size() == 0) {
return 0;
}
// 存储存在的数字
std::unordered_map<int, bool> table;
for(auto ite : nums) {
table[ite] = true;
}
int result = 0;
for(auto ite : nums) {
// 判断当前数字,是否为一个序列的第一个元素
if(table.find(ite-1) == table.end()) {
// 序列第一个元素ite
int begin = ite;
// 目前序列长度1
int temp_result = 1;
// 判断序列后面的数字是否存在
while(table.find(begin+1) != table.end()) {
// 长度++
++temp_result;
// 下一个数字
++begin;
}
// 以begin为序列开头的最大长度
result = max(result, temp_result);
}
}
return result;
}
};







1.先把原始数组元素,放入到table中
2.table判断n+1和n-1是否出现在原始数组中
3.用visited标记,从当前n开始,向上n+1和n-1的数字,记录长度,visited记录元素
4.打擂台,更新result
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.size() <= 0) {
return 0;
}
std::unordered_set<int> table(nums.begin(), nums.end());
std::unordered_set<int> visted;
int result = 0;
for (auto num : table) {
if (visted.find(num) != visted.end()) {
continue;
}
int len = 1;
visted.insert(num);
int right_num = num+1;
while (table.find(right_num) != table.end()) {
++len;
visted.insert(right_num);
++right_num;
}
int left_num = num-1;
while (table.find(left_num) != table.end()) {
++len;
visted.insert(left_num);
--left_num;
}
result = max(result, len);
}
return result;
}
};
426

被折叠的 条评论
为什么被折叠?



