题目地址
LeetCode#747 Largest Number At Least Twice of Others
题目描述
In a given integer array nums
, there is always exactly one largest element.
Find 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, otherwise return -1.
Example 1:
1 | Input: nums = [3, 6, 1, 0] |
Example 2:
1 | Input: nums = [1, 2, 3, 4] |
Note:
nums
will have a length in the range[1, 50]
.- Every
nums[i]
will be an integer in the range[0, 99]
.
解题思路
题目要求是找出数组里满足是最大数且至少是其他数字的两倍的数字,返回其索引,如果没有就返回-1。我们通过一次遍历找出数组的最大值和次大值,然后判断最大值是不是次大值得两倍或者更多,是的话返回最大值索引,不是返回-1。
解题代码【.CPP】
1 | class Solution { |