【LeetCode】128.Longest Consecutive Sequence(Hard)解题报告

【LeetCode】128.Longest Consecutive Sequence(Hard)解题报告

题目地址:https://leetcode.com/problems/longest-consecutive-sequence/description/
题目描述:

  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.

  HashSet.
Solution:

//time : O(n)
//space : O(n)
class Solution {
    public int longestConsecutive(int[] nums) {
        Set set = new HashSet<>();
        int res = 0;
        for(int num : nums){
            set.add(num);
        }
        for(int i=0 ; iint down = nums[i] - 1;
            while(set.contains(down)){
                set.remove(down);
                down--;
            }
            int up = nums[i] + 1;
            while(set.contains(up)){
                set.remove(up);
                up++;
            }
            res = Math.max(res , up-down-1);
        }
        return res;
    }
}

Date:2018年2月20日

你可能感兴趣的:(Array,LeetCode)