1,题目要求
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.
也就是找到数组中最大的数字,如果它比其他所有的数字都要大两倍及以上,则返回其索引值;否则就返回-1。
2,题目思路
题目的要求进行简化,就是找到整个数组中最大的数字和第二大的数字,看最大的是否是第二大的两倍及以上,如果是则返回索引,不是就返回-1;
对于找到这两个数字,其实可以直接用两次for循环来进行暴力查找,时间复杂度为O(n),可以达到题目要求。不过可以进行整合,如果num[i]比最大值大,就更新最大值和第二大的值,并记录最大值的索引。否则,如果num[i]比第二大的值大,则直接更新第二大的值即可。
3,程序源码
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int max = 0;
int maxIndex = 0;
int secondMax=0;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>max)
{
secondMax = max;
max = nums[i];
maxIndex = i;
}
else if(nums[i]>secondMax)
{
secondMax = nums[i];
}
}
return (max/2>=secondMax)?maxIndex:-1;
}
};