Leetcode hot100_128. 最长连续子序列
题目链接:128. 最长连续序列 - 力扣(LeetCode)
贪心方法:从头遍历num数组,不断更新count计数器和最大长度max,用pre记录前一个连续的数字。
1 class Solution { 2 public int longestConsecutive(int[] nums) { 3 if(nums.length==0)return 0; 4 Arrays.sort(nums); 5 int count = 1; 6 int pre = nums[0]; 7 int max = count; 8 for (int i = 1; i < nums.length; i++) { 9 if (nums[i] == nums[i - 1]) 10 continue; 11 if (nums[i] == pre + 1) { 12 count++; 13 if (count > max) 14 max = count; 15 16 } else { 17 count = 1; 18 } 19 pre = nums[i]; 20 } 21 return max; 22 } 23 }
哈希表方法:
回去看了一眼题解发现有的说排序过不了时间限制(?嘿嘿不知道为啥我过了
哈希表方法就是先把数组用哈希表去重并且标记是否存在,然后从头遍历set找到所有连续数组开始的元素开始while循环遍历。全部遍历结束之后找到最大值。
1 class Solution { 2 public int longestConsecutive(int[] nums) { 3 Set<Integer> st = new HashSet<>(); 4 for(int num: nums){ 5 st.add(num); 6 } 7 int max = 0; 8 for(int num: st){ 9 if(!st.contains(num-1)){ 10 int pre = num; 11 int count = 1; 12 while(st.contains(pre+1)){ 13 pre++; 14 count++; 15 } 16 if(max<count)max = count; 17 } 18 } 19 return max; 20 } 21 }

浙公网安备 33010602011771号