Leetcode 747 至少是其他数字两倍的最大数 ( Largest Number At Least Twice of Others *Easy* ) 题解分析

题目介绍

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.
确认在数组中的最大数是否是其余任意数的两倍大及以上,如果是返回索引,如果不是返回-1

示例

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.

提示:

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

简要解析

这个题easy是题意也比较简单,找最大值,并且最大值是其他任意值的两倍及以上,其实就是找最大值跟次大值,比较下就好了

代码

public int dominantIndex(int[] nums) {
    int largest = Integer.MIN_VALUE;
    int second = Integer.MIN_VALUE;
    int largestIndex = -1;
    for (int i = 0; i < nums.length; i++) {
        // 如果有最大的就更新,同时更新最大值和第二大的
        if (nums[i] > largest) {
            second = largest;
            largest = nums[i];
            largestIndex = i;
        } else if (nums[i] > second) {
            // 没有超过最大的,但是比第二大的更大就更新第二大的
            second = nums[i];
        }
    }

    // 判断下是否符合题目要求,要是所有值的两倍及以上
    if (largest >= 2 * second) {
        return largestIndex;
    } else {
        return -1;
    }
}

通过图

第一次错了是把第二大的情况只考虑第一种,也有可能最大值完全没经过替换就变成最大值了