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]
.
Hints:
- Scan through the array to find the unique largest element
m
, keeping track of it’s indexmaxIndex
. - Scan through the array again.
- If we find some
x != m
withm < 2*x
, we should return-1
. - Otherwise, we should return
maxIndex
.
1 |
class { |
细节
- 要返回的是index,不是max,所以要记录maxindex。
总结
-
O(n^2)time,O(1)space
-
O(n)找到最大数,并记录索引,一定要记录索引啊!!因为要返回的是index!
- O(n)重新遍历,如果发现有 x!=m 且 2x>m,返-1
近期评论