Java O(1) space, O(n) solution


  • 0
    C
    public int thirdMax(int[] nums) {
            Arrays.sort(nums);
            int count = 1, i = nums.length-1;
            while(i > 0) {
                while(i > 0 && nums[i] == nums[--i]);
                if(i == 0 && nums[i] == nums[i+1]) break;
                count++;
                if(count == 3) break;
            }
            
            return count < 3 ? nums[nums.length-1] : nums[i];
        }
    

  • 1
    C

    Sort is O(N lg N)


  • 0
    C

    @cysmith Yeah, you are right. Thanks for pointing out.


Log in to reply
 

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