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.
思路:
建立一个hash表,查找是否在表里面,向前和向后查找,比如对于数组元素100,然后查找是否存在99,98...等,还有是否
存在101,102...等。表里不存在就继续查找数组中别的元素。
比如,对于4,往左查找到3,2,1等,最长序列长度就为4。
还有就是,如果已经查到某元素,然后就将其在表里删除,能够减少后续查找次数。
int longestConsecutive(vector<int>& nums) { if (nums.size() == 0)return 0; unordered_set<int>record(nums.begin(),nums.end());//hash表格 int result = 1; for (int i = 0; i < nums.size();i++) { if (record.find(nums[i]) == record.end()) continue;//没有找到i record.erase(nums[i]);//如果在的话就删除i,减少set的规模 int pre = nums[i] - 1, next = nums[i] + 1;//向前和向后查找 while (record.find(pre) != record.end()) { record.erase(pre); pre--; } while (record.find(next) != record.end()) { record.erase(next); next++; } result = max(result,next-pre-1); } return result; }
参考:
https://discuss.leetcode.com/topic/16483/a-simple-c-solution-using-unordered_set-and-simple-consideration-about-this-problem