HashMap Not very smart, but easy to get


  • 0
    W
    public class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer, int[]> map = new HashMap<>();
        int max = 1;
        for(int i = 0; i < nums.length; i++){
            int[] temp = new int[2];
            temp[0] = nums[i];
            temp[1] = nums[i];
            if(!map.containsKey(nums[i])){
                if(map.containsKey(nums[i] - 1)){
                    int[] res1 = map.get(nums[i] - 1);
                    temp[0] = res1[0];//record left boundary;
                }
                if(map.containsKey(nums[i] + 1)){
                    int[] res2 = map.get(nums[i] + 1);
                    temp[1] = res2[1];//record right boundary
                }
                map.put(nums[i], temp);
                max = Math.max(max, temp[1] - temp[0] + 1);
                int[] left = map.get(temp[0]);
                int[] right = map.get(temp[1]);
                left[1] = temp[1];//left boundary updates right limit
                right[0] = temp[0];//right boundary updates left limit
                map.put(temp[0], left);//left boundary updates right limit
                map.put(temp[1], right);//right boundary updates left limit
            }
            
        }
        return max;
    }
    

    }


Log in to reply
 

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