Third Maximum Number

2019-09-10 18:45:26 浏览数 (1)

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

代码语言:javascript复制
Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

代码语言:javascript复制
Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

代码语言:javascript复制
Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

我的答案:

代码语言:javascript复制
class Solution {
    public int thirdMax(int[] nums) {
        sort(nums);
        int a = 1;
        int thrid = nums[nums.length - 1];
        for (int i = nums.length-1; i >=0; i--) {
            int num = nums[i];
            if (num < thrid) {
                a  ;
                thrid = num;
            }
            if (a == 3) {
                break;
            }
        }
        if (a < 3) {
            return nums[nums.length - 1];
        }
        return thrid;
    }
    
    private static int partition(int[] arr, int l, int r){

        int v = arr[l];
        int j = l; // arr[l 1...j] < v ; arr[j 1...i) > v
        for( int i = l   1 ; i <= r ; i    )
            if( arr[i]< v ){
                j   ;
                swap(arr, j, i);
            }
        swap(arr, l, j);
        return j;
    }

    private static void sort(int[] arr, int l, int r){
        if( l >= r )
            return;
        int p = partition(arr, l, r);
        sort(arr, l, p-1 );
        sort(arr, p 1, r);
    }


    public static void sort(int[] arr){
        int n = arr.length;
        sort(arr, 0, n-1);
    }
    private static void swap(int[] arr, int i, int j) {
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

大神的答案:

代码语言:javascript复制
 public int thirdMax(int[] nums) {
        Integer max1 = null;
        Integer max2 = null;
        Integer max3 = null;
        for (Integer n : nums) {
            if (n.equals(max1) || n.equals(max2) || n.equals(max3)) continue;
            if (max1 == null || n > max1) {
                max3 = max2;
                max2 = max1;
                max1 = n;
            } else if (max2 == null || n > max2) {
                max3 = max2;
                max2 = n;
            } else if (max3 == null || n > max3) {
                max3 = n;
            }
        }
        return max3 == null ? max1 : max3;
}

0 人点赞