Not concise But directly Solve this problem


  • 0
    J

    I just find the largest , then the second, last is third

    public int thirdMax(int[] nums) {
            int max = nums[0];
            for (int i = 1; i < nums.length; i++){
                max = Math.max(max, nums[i]);
            }
            int mid = max;
            for (int i = 0; i < nums.length; i++){
                if (nums[i] != max){
                    mid = nums[i];
                    break;
                }
            }
            if (max == mid){
                return max;
            }
            for (int i = 0; i < nums.length; i++){
                if (nums[i] != max && nums[i] > mid){
                    mid = nums[i];
                }
            }
            int small = mid;
            for (int i = 0; i < nums.length; i++){
                if (nums[i] != max && nums[i] != mid){
                    small = nums[i];
                    break;
                }
            }
            if (small == mid){
                return max;
            }
            for (int i = 0; i < nums.length; i++){
                if (nums[i] != max && nums[i] != mid && 
    nums[i] > small){
                    small = nums[i];
                }
            }
           return small;
        }
    

Log in to reply
 

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