14 lines Easy Java Solution


  • 0
    M
         public int longestConsecutive(int[] nums) {
            int maxLength = 0;
            //validation
            if(nums == null || nums.length == 0) return 0;
            HashSet<Integer> hashSet = new HashSet<Integer>();
            //populate th has set
            for(int num: nums)hashSet.add(num);
            for(int i=0;i<nums.length;i++){
                if(!hashSet.contains(nums[i]-1)){
                    //this is the start of the sequence. count the consecutive numbers from here
                    int temp = nums[i];
                    while(hashSet.contains(temp)){
                        maxLength = Math.max(maxLength, temp-nums[i]+1);
                        temp++;
                    }
                }
            }
            return maxLength;
        }
    }

Log in to reply
 

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