前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Third Maximum Number

Third Maximum Number

作者头像
luozhiyun
发布2019-09-10 18:45:26
3440
发布2019-09-10 18:45:26
举报

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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-02-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档