O(n) java solution, super easy to understand


  • 0
    L

    First add all numbers to a set
    Then find out all the start number
    Last get the length

    public class Solution {
        public int longestConsecutive(int[] nums) {
            if (nums.length == 0) {
                return 0;
            }
            Set<Integer> set = new HashSet<>();
            for (int i : nums) {
                set.add(i);
            }
            Set<Integer> candidates = new HashSet<>();
            for (int i : nums) {
                if (!set.contains(i - 1) && set.contains(i + 1)) {
                    candidates.add(i);
                }
            }
            int maxLength = 1;
            for (Integer i : candidates) {
                maxLength = Math.max(maxLength, getLength(set, i));
            }
            return maxLength;
        }
        
        private int getLength(Set<Integer> set, int i) {
            int length = 1;
            while (set.contains(i + 1)) {
                length++;
                i++;
            }
            return length;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.