Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
题目大意:给一个无序数组,找出最大的连续元素的长度。
说真的,一开始这题,我想半天只想到用boolean数组mark,后来看了别人的才发现可以用set做。
解题思路:
把所有的数组放到set中,然后遍历数组的元素,然后分别向前、向后寻找set中是否存在,记录max。
public int longestConsecutive(int[] nums) { if(nums==null||nums.length==0){ return 0; } Set<Integer> set = new HashSet<>(); for(int num:nums){ set.add(num); } int max = 0; for(int i=0;i<nums.length;i++){ Integer num = nums[i]; int cnt = 1; while(set.contains(--num)){ cnt++; set.remove(num); } num=nums[i]; while(set.contains(++num)){ cnt++; set.remove(num); } max=Math.max(max,cnt); } return max; }