Longest Consecutive Sequence

Problem:
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.

Analysis:
  1. store all numbers to set
  2. iterate through the array, check if n - 1 exist
  3. n - 1 not exist, current number is the start of the sequence. 
  4. count current sequence with set
HashMap is power full don't afraid to use it. 
Solution:


class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        Set<Integer> numsSet = HashSet<>();
        int res = 0;
        for (int n: nums) {
            numsSet.add(n);
        }

        for (int n: nums) {
            if (!numsSet.contains(n - 1)) {
                int curNum = n;
                int curRes = 1;
                while (numsSet.contains(curNum++)) {
                    curRes++;
                }
                res = Math.max(res, curRes);
            }
        }

        return res;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List