在一個給定的數(shù)組nums中,總是存在一個最大元素 。
查找數(shù)組中的最大元素是否至少是數(shù)組中每個其他數(shù)字的兩倍们镜。
如果是,則返回最大元素的索引润歉,否則返回-1模狭。
示例 1:
輸入: nums = [3, 6, 1, 0]
輸出: 1
解釋: 6是最大的整數(shù), 對于數(shù)組中的其他整數(shù),
6大于數(shù)組中其他元素的兩倍。6的索引是1, 所以我們返回1.
示例 2:
輸入: nums = [1, 2, 3, 4]
輸出: -1
解釋: 4沒有超過3的兩倍大, 所以我們返回 -1.
提示:
nums 的長度范圍在[1, 50].
每個 nums[i] 的整數(shù)范圍在 [0, 99].
分析:
找到最大值maxn踩衩、它對應的下標idx和次大值sec嚼鹉,如果次大值sec的兩倍比maxn大說明不滿足條件返回-1,否則返回idx
C
int dominantIndex(int* nums, int numsSize){
int i,max=0,sec=0,index=-1;
for(i=0;i<numsSize;i++){
if(nums[i]>=max){
sec=max;
max=nums[i];
index=i;
}else if(nums[i]>sec){
sec=nums[i];
}
}
if(sec*2>max)
return -1;
else
return index;
}
C++
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int maxn = 0, idx = -1, sec = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > maxn) {
sec = maxn;
maxn = nums[i];
idx = i;
} else if(nums[i] > sec){
sec = nums[i];
}
}
return sec * 2 > maxn ? -1 : idx;
}
};