public int longestConsecutive(int[] nums) { int result = 0; Set<Integer> set = new HashSet<>(); for(int i = 0 ; i < nums.length ; i++) { set.add(nums[i]); } for(int i = 0; i < nums.length ; i++) { if(!set.contains(nums[i] -1)) //找到起点 { int curValue = nums[i]; int curLen = 1; while(set.contains(curValue+1)) //寻找最长的连续序列 { curLen++; curValue++; } result = Math.max(result,curLen); } } return result; }
利用Hashset查找元素时间复杂度近似为O(1)