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;
    }
}
posted @ 2018-03-25 10:02  optor  阅读(76)  评论(0编辑  收藏  举报