128. 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.

tag: set, two pointer

class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        Set<Integer> hash = new HashSet<>();

        for (int num : nums){
            hash.add(num);
        }

        int ans = 1;
        for (int i = 0; i < nums.length; i++){
            int low = nums[i], high = nums[i];
            while (hash.contains(high + 1)){
                hash.remove(high + 1);
                high++;
            }
            while (hash.contains(low - 1)){
                hash.remove(low - 1);
                low--;
            }
            //System.out.println("i: " + i + " high: " + high + " low: " + low);
            ans = Math.max(ans, high - low + 1);
            hash.remove(nums[i]);
        }

        return ans;
    }
}

results for ""

    No results matching ""