1. 程式人生 > >128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

set 下一個 cto () num 叠代 重新 gpo pro

歡迎fork and star:Nowcoder-Repository-github

128. Longest Consecutive Sequence

題目

 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. 

解析

  • I have seen a lot of discussion about this problem.In my opinion,it is not correct to use set(which is ordered),because very time we insert an element to a ordered set,it will cost O(n),so the total complexity is O(nlogn),which violates the request of the problem.So here we use an unordered_set,and one is enough.

  • Besides,to think about this problem,one principle issue we should realize is that usually when we want to reduce the time complexity,we have to increase the space complexity.In this case,if we want to access an element within O(1),we have to use hash table.

  • 另外思考一下hash的叠代器實現方法??


// Longest Consecutive Sequence
class Solution_128 { public: int longestConsecutive(vector<int> &num) { if (num.size()==0) { return 0; } unordered_set<int> hash(num.begin(), num.end()); //O(n),插入hash表中 int ret = 1; for (auto cur:num) //遍歷元素O(n) { if (hash.find(cur)==hash.end()) //未找到當前元素 { continue; } hash.erase(cur); int pre = cur - 1, next = cur + 1; //下一個連續序列重新賦值 while (hash.find(pre)!=hash.end()) //hash的叠代器怎麽實現? { hash.erase(pre); pre--; } while (hash.find(next)!=hash.end()) { hash.erase(next); next++; } ret = max(ret, next - pre - 1); // bug : next - pre - 1 } return ret; } };

題目來源

  • 128. Longest Consecutive Sequence

128. Longest Consecutive Sequence