题目大意:给你一个数组,问你其中最大的数是不是比剩下的数大2倍以上,返回这样的数的索引。如果不存在,返回-1.
Problem:
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 2 3 4 |
Input: nums = [3, 6, 1, 0] Output: 1 Explanation: 6 is the largest integer, and for every other number in the array x, 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. |
Example 2:
1 2 3 |
Input: nums = [1, 2, 3, 4] Output: -1 Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. |
Note:
nums
will have a length in the range[1, 50]
.- Every
nums[i]
will be an integer in the range[0, 99]
.
Solution:
C++
1 2 3 4 5 6 7 8 9 10 11 12 |
// Author: Huahua // Running time: 6 ms class Solution { public: int dominantIndex(vector<int>& nums) { auto it1 = max_element(nums.begin(), nums.end()); const int max1 = *it1; *it1 = -1; const int max2 = *max_element(nums.begin(), nums.end()); return max1 >= max2 * 2 ? distance(nums.begin(), it1) : -1; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment