java solution using HashSet


  • 0
    N

    public class Solution {
    public int longestConsecutive(int[] nums) {
    int length = nums.length;
    if(length == 0){
    return 0;
    }
    if(length == 1){
    return 1;
    }

        HashSet<Integer> set = new HashSet<Integer>();
        for(int i : nums){
            set.add(i);
        }
        
        int longest = 1;
        
        for(int i = 0; i<length; i++){
            int val = nums[i];
            if(set.contains(val)){
                int len = 1;
                set.remove(val);
                while(set.contains(++val)){
                    len++;
                    set.remove(val);
                }
                val = nums[i];
                while(set.contains(--val)){
                    len++;
                    set.remove(val);
                }
                longest = Math.max(len, longest);
            }
        }
        return longest;
    }
    

    }


Log in to reply
 

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