2022-3-30 高频题 day3
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
1 class Solution { 2 public int longestConsecutive(int[] nums) { 3 Set<Integer> set=new HashSet<>(); 4 //Map<Integer,Integer> map=new HashMap<>(); 5 for (int x:nums) { 6 set.add(x); 7 //map.put(x,1); 8 } 9 int ans=0,cur=0; 10 for (int x:set){ 11 cur=0; 12 if (!set.contains(x-1)) { 13 int t=x; 14 while (set.contains(t)){ 15 cur++; 16 t++; 17 } 18 ans=Math.max(ans,cur); 19 } 20 } 21 return ans; 22 } 23 }
思路:对于每一个数字 判断前一个数是否在,在的话直接跳过,因为可以构成更长的序列,否则以当前数字判断序列长度。
浙公网安备 33010602011771号