Java O(n) solution, didn't pass [1,1,2]


  • 0
    M

    Here's my solution, which did not pass [1,1,2].
    I guess this is a problem with initial value of int.min, but I don't know what else to do. Can anybody helps? Thanks so much

        public int thirdMax(int[] nums) {
            int first = Integer.MIN_VALUE;
            int second = Integer.MIN_VALUE;
            int third = Integer.MIN_VALUE;
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] > first) {
                    third = second;
                    second = first;
                    first = nums[i];
                } else if(nums[i] > second && nums[i] != first) {
                    third = second;
                    second = nums[i];
                } else if(nums[i] > third  && nums[i] != first && nums[i] != second) {
                    third = nums[i];
                } else {
                    continue;
                }
            }
            if(nums.length < 3) {
                return first;
            }
            return third;
        }
    }

  • 0
    P

    I had the same idea you did. I don't think this way works unless you use Set. If the set size is less than 3 return the max element. This IMO is a really bad way of doing it though.


Log in to reply
 

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