Courtesy @dchen0215 pretty neat Java solution.


  • 0
    V
    public class Solution {
        public int longestConsecutive(int[] nums) {
            Map<Integer, Integer> store = new HashMap<>();
            int i = 0, maxLen = 0;
            while (i < nums.length) {
                if (!store.containsKey(nums[i])) {
                    int leftSeqLen = (store.containsKey(nums[i] - 1)) ? store.get(nums[i] - 1) : 0;
                    int rightSeqLen = (store.containsKey(nums[i] + 1)) ? store.get(nums[i] + 1) : 0;
                    
                    store.put(nums[i], leftSeqLen + rightSeqLen + 1);
                    /**
                       This is the key Idea, because the lists are continues, they must end at num[i] - leftSeqLen and num[i] + rightSeqLen.
                    **/
                    store.put(nums[i] - leftSeqLen, leftSeqLen + rightSeqLen + 1);
                    store.put(nums[i] + rightSeqLen, leftSeqLen + rightSeqLen + 1);
                    
                    maxLen = Math.max(maxLen, leftSeqLen + rightSeqLen + 1);
                }
                i++;
            }
            
            return maxLen;
        }
    }
    

Log in to reply
 

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