LeetCode.747. 至少是其他数字两倍的最大数

在一个给定的数组nums中,总是存在一个最大元素 。

查找数组中的最大元素是否至少是数组中每个其他数字的两倍。

如果是,则返回最大元素的索引,否则返回-1。

示例 1:

输入: nums = [3, 6, 1, 0]
输出: 1
解释: 6是最大的整数, 对于数组中的其他整数,
6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.

示例 2:

输入: nums = [1, 2, 3, 4]
输出: -1
解释: 4没有超过3的两倍大, 所以我们返回 -1.

提示:

  1. nums 的长度范围在[1, 50].
  2. 每个 nums[i] 的整数范围在 [0, 99].

分析:
遍历两遍,第一遍找出最大值,第二遍判断该最大值是否至少是其他数的两倍,需要注意两点细节:
1. 当数组长度为 1 时,返回的是 0 而不是 -1
2. 第二遍遍历比较时,需要将最大值本身排除

class Solution {
    public int dominantIndex(int[] nums) {
        int len = nums.length;
        if (len == 1)
            return 0;
        int max = 0;
        for (int i = 1; i < len; i++) {
            if (nums[max] < nums[i])
                max = i;
        }
        for (int i : nums) {
            if (nums[max] < i * 2 && nums[max] != i)
                return -1;
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/liyuanyue2017/article/details/81167459
今日推荐