I don't know why it's hard, and my simple O(n) solution


  • -1
    U
     public int longestConsecutive(int[] nums) {
            if (nums.length <= 1) {
                return nums.length;
            }
            
            Arrays.sort(nums);
            
            int max = 1;
            int n = 1;
            int prev = nums[0];
            
            for (int i = 1; i < nums.length; i++) {
                    if (nums[i] == prev + 1) {
                       n++;
                       max = Math.max(max, n);
                    } else if (nums[i] != prev) {
                        n = 1;
                    }
                    prev = nums[i];
            }
            
            return max;
        }
    

  • 0
    J

    @ulyx your sort(..) is O(nlogn)


Log in to reply
 

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