1. 程式人生 > >leetcode (Largest Number At Least Twice of Others)

leetcode (Largest Number At Least Twice of Others)

Title:Largest Number At Least Twice of Others   747

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/largest-number-at-least-twice-of-others/

 

1. 找到最大值並記錄其下標,找到第二大值

時間複雜度:O(n),兩次一層for迴圈,需要遍歷整個陣列。

空間複雜度:O(1),沒有申請額外的空間。

    /**
     * 找到最大值並記錄其下標,找到第二大值,然後最大值除以第二大值來判斷,需要注意:1、陣列只有一個數,2、第二大值為0
     * @param nums
     * @return
     */
    public static int dominantIndex(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return -1;
        }

        if (nums.length == 1) {
            return 0;
        }

        int firstMax = Integer.MIN_VALUE;
        int secondMax = Integer.MIN_VALUE;
        int index = -1;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > firstMax) {
                firstMax = nums[i];
                index = i;
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > secondMax && nums[i] < firstMax) {
                secondMax = nums[i];
            }
        }

        if (secondMax == 0) {
            return index;
        }

        if (firstMax / secondMax >= 2) {
            return index;
        }
        else {
            return -1;
        }

    }

2.  直接找到最大值的下標,然後比較最大值與其餘數乘以2

時間複雜度:O(n),兩次一層for迴圈,需要遍歷整個陣列。

空間複雜度:O(1),沒有申請額外的空間。

    /**
     * 直接找到最大值的下標,然後比較最大值與其餘數乘以2
     * @param nums
     * @return
     */
    public static int dominantIndex1(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return -1;
        }

        int maxIndex = 0;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (i != maxIndex && nums[maxIndex] < nums[i] * 2) {
                return -1;
            }
        }

        return maxIndex;

    }