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:
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
/*
执行用时 : 0 ms, 在Largest Number At Least Twice of Others的C提交中击败了100.00% 的用户
内存消耗 : 7.1 MB, 在Largest Number At Least Twice of Others的C提交中击败了79.49% 的用户
*/
int dominantIndex(int* nums, int numsSize){
//由题目可知最大值总是存在,即数组元素个数>0,所以对numsSize=0的情况可以不用考虑
//由测试用例可知:只有一个元素时满足题设条件
if(numsSize==1){
return 0;
}
//记录最大的初始指向第一个元素
int firstmax=nums[0];
int k=0;//记录最大的下标
//记录第二大的,题中给出数组值的范围在0~99,所以初始值设置为-1(其他<0的数亦可)。
int secondmax=-1;
int i;
for(i=1;i<numsSize;i++){
if(nums[i]>firstmax){
//当前元素最大,则firstmax成为第二大。需维护三个变量
secondmax=firstmax;
firstmax=nums[i];
k=i;
}
else if(nums[i]>secondmax){
//如果当前元素是第二大,则该变记录的第二大
secondmax = nums[i];
}//if
}//for
if(firstmax >= secondmax*2){
return k;
}
else{
return -1;
}
}
后记:
需注意当前元素不是最大时有可能是第二大,所以需要再比较确定是否是第二大。