算法描述:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
解题思路:时间复杂度要求O(n),首先想到hash。
int longestConsecutive(vector<int>& nums) { if(nums.size()==0) return 0; unordered_map<int, int> map; for(int i =0 ; i < nums.size(); i++){ map[nums[i]]++; } int maxLength = 0; for(int i=0; i < nums.size(); i++){ int left = nums[i]-1; int right = nums[i]+1; while(right < INT_MAX && map.find(right)!=map.end()){ map.erase(right++); } while(left > INT_MIN && map.find(left)!=map.end()){ map.erase(left--); } maxLength = max(maxLength,right - left -1); } return maxLength; }