最近經常閑的無聊,於是就做做leetcode的題了,目測好像都不是很難.
不過呢,閑的無聊還是記錄下某些做了的題.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
一看呢,就是排序,然后找就好了,但是要求是O(n),排序明顯是個O(n*logn)的算法.
只是找連續的嘛,我們可以把所有的數字都存入hash表,然后隨意從某個數字開始找他的前面和后面那個是否存在.
然后得到一個最大的長度.當然找過的就可以刪掉了...你想,一個連續的序列,你從中間任意位置開始往兩邊找不都一樣么.
所以只要找過就可以刪掉了.
class Solution {
public:
set<int> flag;
int findBound(int n , bool asc){
int ans = 0;
set<int>::iterator iter;
while((iter = flag.find(n)) != flag.end()){
flag.erase(iter);
ans ++;
if(asc) n-- ; else n++;
}
return ans;
}
int longestConsecutive(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = 0;
flag.clear();
for(int i = 0 ; i < num.size() ; i++)
flag.insert(num[i]);
for(int i = 0 ; i < num.size(); i++){
ans = max(findBound(num[i],true) + findBound(num[i]+1,false) , ans);
}
return ans;
}
};
----update----
class Solution {
public:
int longestConsecutive(vector<int> &num) {
s.clear();
for (int i = 0; i < num.size(); i++) {
s.insert(num[i]);
}
int ans = 0;
for (int i = 0; i < num.size(); i++) {
ans = max(ans, bound(num[i], true) + bound(num[i] + 1, false));
}
return ans;
}
private:
unordered_set<int> s;
int bound(int num, bool asc) {
int cnt = 0;
for (auto iter = s.find(num); iter != s.end(); iter = s.find(num)) {
s.erase(iter);
if (asc) num--; else num++;
cnt++;
}
return cnt;
}
};
