129.Longest Consecutive Sequence

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.

Subscribe to see which companies asked this question

  Step1:先把所有的元素都存入到set中;

  Step2:遍历set中的元素,针对这个元素把所有连续比它大的元素都删除,然后再把所有比它小的元素都删除,并记录下个数;

  Step3:继续遍历set中剩下的元素,重复Step2。

/**
	 * 给定一个未排序的数组,求该数组中元素连续的最大长度。
	 * Given [100, 4, 200, 1, 3, 2],
	 * The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
	 * 思路:
	 * Step1:先把所有的元素都存入到set中;
	 * Step2:遍历set中的元素,针对这个元素把所有连续比它大的元素都删除,然后再把所有比它小的元素都删除,并记录下个数;
	 * Step3:继续遍历set中剩下的元素,重复Step2。
	 * @date 20160512 
	 */
	public int longestConsecutive(int[] nums) {
		
		int len = nums.length;
		if(len <= 0){
			return 0;
		}
		int result = 1;
        Set<Integer> set = new HashSet<Integer>(len);
        for(int i=0;i<len;i++){
        	set.add(nums[i]);
        }
        
        Iterator<Integer> it = set.iterator();
        while(!set.isEmpty()){
        	it = set.iterator();
        	int element = it.next();
        	set.remove(element);
        	int next = element+1;//比element大的元素
        	int pre = element-1;
        	while(set.contains(next)){
        		set.remove(next);
        		next++;
        	}
        	while(set.contains(pre)){
        		set.remove(pre);
        		pre--;
        	}
        	if(result < next-pre-1){
        		result = next-pre-1;
        	}
        }
        return result;
    }

你可能感兴趣的:(129.Longest Consecutive Sequence)