414. Third Maximum Number

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了414. Third Maximum Number相关的知识,希望对你有一定的参考价值。

原题链接:https://leetcode.com/problems/third-maximum-number/description/
我的解答:

import java.util.Arrays;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.thirdMax(new int[]{3, 2, 1}));
        System.out.println(s.thirdMax(new int[]{1, 2}));
        System.out.println(s.thirdMax(new int[]{2, 2, 3, 1}));
    }

    /**
     * 方法一:我自己想的方法,说实话有点复杂,但是提交结果是:84.59 %
     *
     * @param nums
     * @return
     */
    public int thirdMax1(int[] nums) {
        Arrays.sort(nums);

        int[] res = new int[3];
        int k = 0;
        for (int i = nums.length - 1; i > 0; i--) {
            if (k == 3) {
                break;
            }
            if (k < 3 && nums[i] != nums[i - 1]) {
                res[k] = nums[i];
                k++;
            }
        }

        if (k < 3 && nums[0] != nums[1]) {
            res[k] = nums[0];
            k++;
        }

        if (k == 3) {
            return res[2];
        } else {
            return nums[nums.length - 1];
        }
    }

    // 讨论区别人的答案啦,不得不说高手就是牛逼,但是这个答案并能不通用,接下来去看看下一题:
    public int thirdMax(int[] nums) {
        long min = Long.MIN_VALUE, a = min, b = min, c = min;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == a || nums[i] == b || nums[i] == c) {
                continue;
            }
            if (nums[i] > c) {
                a = b;
                b = c;
                c = nums[i];
            } else if (nums[i] > b) {
                a = b;
                b = nums[i];
            } else if (nums[i] > a) {
                a = nums[i];
            }
        }

        return a == min ? (int)c : (int)a;
    }
}

以上是关于414. Third Maximum Number的主要内容,如果未能解决你的问题,请参考以下文章

414. Third Maximum Number

414. Third Maximum Number

414. Third Maximum Number

414. Third Maximum Number

Leetcode-414 Third Maximum Number

414. Third Maximum Number