Easy to Understand using HashSet


  • 0
        public int longestConsecutive(int[] nums) {
            HashSet<Integer> set = new HashSet<Integer>();
    
            //Adding all values to the hashset
            for(int n:nums) {
                set.add(n);
            }
            int len = 0;
            for(int n:nums) {
                if(!set.contains(n-1)) {
                    int temp = n;
                    while(set.contains(temp)) {
                        temp++;
                    }
                
                    if(len < temp - n) {
                        len = temp - n;
                    }
                }   
            }
            
            return len;
        }

Log in to reply
 

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