[leetcode] longest consecutive sequence
2037 ワード
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.
この問題の私の最初の反応はbitmapですが、mappingが過ぎた後、どのようにこのbitmapを検索するかはまた大きな問題です.
その実用的なhashでいいので、まず配列をhashテーブルに入れて、O(n)
表から要素を手に入れた後、その前後の要素を探してhash表にいないで、現在の要素を削除することを見つけました.
検索と削除のたびにO(1)であるためhashテーブルの遍歴複雑度もO(n)である.
ついでにSTLの中のhash削除の使い方を貼ります
by position (1)
by key (2)
range (3)
Versions(1)(3)削除された要素の次の要素を返すiterator
Version(2)削除された要素の数を返す
この問題の私の最初の反応はbitmapですが、mappingが過ぎた後、どのようにこのbitmapを検索するかはまた大きな問題です.
その実用的なhashでいいので、まず配列をhashテーブルに入れて、O(n)
表から要素を手に入れた後、その前後の要素を探してhash表にいないで、現在の要素を削除することを見つけました.
検索と削除のたびにO(1)であるためhashテーブルの遍歴複雑度もO(n)である.
ついでにSTLの中のhash削除の使い方を貼ります
by position (1)
iterator erase ( const_iterator position );
by key (2)
size_type erase ( const key_type& k );
range (3)
iterator erase ( const_iterator first, const_iterator last );
Versions(1)(3)削除された要素の次の要素を返すiterator
Version(2)削除された要素の数を返す
class Solution {
public:
int longestConsecutive(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unordered_set<int> hash;
for(int i = 0; i < num.size(); i++){
hash.insert(num[i]);
}
int ret = 0;
int cnt;
unordered_set<int>::iterator it;
int cur_elem;
int tmp_elem;
while(!hash.empty()){
it = hash.begin();
cur_elem = *it;
hash.erase(it);
tmp_elem = cur_elem;
cnt = 1;
while((it = hash.find(tmp_elem + 1))!= hash.end()){
hash.erase(it);
tmp_elem++;
cnt++;
}
tmp_elem = cur_elem;
while((it = hash.find(tmp_elem - 1))!= hash.end()){
hash.erase(it);
tmp_elem--;
cnt++;
}
ret = max(ret, cnt);
}
return ret;
}
};