Description:
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:
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:
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]
.
思路:本题题意是找出数组中最大元素,该最大元素是比其他元素大两倍的元素,若存在返回其数组下标,不存在则返回-1。想法比较简单,首先对数组排序,比较最大的两个数是否满足大于两倍的关系,最后返回数组下标。
C++ 代码
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int n=nums.size();
if(n==1)
return 0;
vector<int>A(nums.begin(),nums.end());
sort(A.rbegin(),A.rend());
if(A[0]<2*A[1])
return -1;
for(int i=0;i<n;i++)
{
if(nums[i]==A[0])
return i;
}
return -1;
}
};
运行时间:4ms
运行内存:8.5M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于