题目描述:
https://leetcode.com/problems/longest-consecutive-sequence/
Code:
//mycode
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
set<int> tp_st( nums.begin() , nums.end() );
vector<int> tp_nums( tp_st.begin(), tp_st.end() );
if( tp_nums.size() != 0){
int maxlength = 1;
int begin = 0 ;
sort(tp_nums.begin(), tp_nums.end());
for (int i = 0; i < tp_nums.size() -1 ; i++) {
if (tp_nums.at(i+1) != tp_nums.at(i) + 1) {
int tp_len = i - begin + 1;
if (tp_len > maxlength) {
maxlength = tp_len;
}
begin = i + 1;
}
}
int tp_len = tp_nums.size() - begin ;
if (tp_len > maxlength) {
maxlength = tp_len;
}
return maxlength;
}else{
return 0;
}
}
};
//other people's good solution
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int res = 0;
unordered_map<int, int> m;
for (int d : nums) {
if (!m.count(d)) {
int left = m.count(d - 1) ? m[d - 1] : 0;
int right = m.count(d + 1) ? m[d + 1] : 0;
int sum = left + right + 1;
m[d] = sum;
res = max(res, sum);
m[d - left] = sum;
m[d + right] = sum;
}
}
return res;
}
};
网友评论