[JAVA] Two HashMap with left and right length / T : O(N), S : O(N)


  • 0
    J
    class Solution {
        public int longestConsecutive(int[] nums) {
            HashMap<Integer, Integer> left = new HashMap<Integer, Integer>();
            HashMap<Integer, Integer> right  = new HashMap<Integer, Integer>();
            
            int count = 0;
            for(int num : nums){
                int leftVal = left.getOrDefault(num-1,0);
                int rightVal = right.getOrDefault(num+1,0);
                int len = 1 + leftVal + rightVal;
                
                if(left.getOrDefault(num + rightVal, 0) < len)
                    left.put(num + rightVal, len);
                if(right.getOrDefault(num - leftVal, 0) < len)
                    right.put(num - leftVal, len);
    
                if(len > count)
                    count = len;
            }
            
            return count;
        }
    

Log in to reply
 

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