标签:length contain ret out HERE ref eve current seq
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. //solution 1 : time nlogn (sorting ) class Solution { public int longestConsecutive(int[] nums) { if(nums.length <= 1){ return nums.length; } Arrays.sort(nums); int[] count = new int[nums.length]; for(int i= 0; i < nums.length; i++){ count[i] = 1; } int max = 0; for(int i = 1; i < nums.length; i++){ if(nums[i] - 1 == nums[i-1]){ count[i] = count[i-1] + 1; }else if(nums[i] == nums[i-1]){ count[i] = count[i-1]; } max = Math.max(max, count[i]); } return max; } } // solution 2 : time O(n) class Solution { public int longestConsecutive(int[] nums) { if(nums == null || nums.length == 0) return 0; // put every element into a set // suppose every num is the start of the consecutive sequence // check if current element + 1, + 2 .. exists in the set or not // update the res int res = 1; HashSet<Integer> set = new HashSet<>(); for(int num : nums) set.add(num); for(int i = 0; i < nums.length; i++){ int num = nums[i]; int len = 1; while(set.contains(num + 1)){ len++; num += 1; } res = Math.max(res, len); } return res; } }
128. Longest Consecutive Sequence
标签:length contain ret out HERE ref eve current seq
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9913069.html