Simple Java solution with sort (N*logN)


  • -3
    L
     public int longestConsecutive(int[] nums) {
        if(nums.length < 2) return nums.length;
        Arrays.sort(nums);
        int max = 1;
        for (int i = 1, tmp = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                continue;
            } else if (nums[i] == nums[i - 1] + 1) {
                if (++tmp > max) max = tmp;
            } else {
                tmp = 1;
            }
        }
        return max;
    }

  • 2
    J
    Your algorithm should run in O(n) complexity.

Log in to reply
 

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