Largest Number At Least Twice of Others - LeetCode

# Description

You are given an integer array  nums  where the largest integer is unique.

Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return  -1  otherwise.

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.

Constraints:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in  nums  is unique.

# Note

記一下這題,因為求 Max 時可以多用下 java 的 stream api。

第一個解法用 stream 的就是直接先求出最大值,然後再遍歷數組。如果剛好最大值是等於當前的元值(相當於找到自己)那就紀錄一下自己的 index。否則再看看,如果 maxValue < 2 * nums[i] (題目要求)的話,那就直接返回 -1 了

public int dominantIndex(int[] nums) {
         int maxIndex = -1;
         int maxValue = Arrays.stream(nums).max().getAsInt(); 
         for (int i = 0; i < nums.length; i++) {
             if(maxValue == nums[i]) maxIndex = i;
             else if (maxValue < 2 * nums[i]) return -1;
         }
        return maxIndex;
         
    }

第二個就不用 stream 了,在遍歷的時候找最大值,再然第二大的值。
因為只要 maxValue > 2 * secondMaxValuemaxValue 也肯定會比其他的數值大至少 2 倍。

public int dominantIndex(int[] nums) {
        int maxValue = -1, secondMax = -1, maxIndex;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > maxValue) {
                secondMax = maxValue;
                maxValue = nums[i];
                maxIndex = i;
            }
            else if (nums[i] > secondMax) {
                secondMax = nums[i];
            }
        }
        return maxValue >= secondMax * 2 ? maxIndex : -1;
         
    }