在一個給定的數組nums
中,總是存在一個最大元素 。
查找數組中的最大元素是否至少是數組中每個其他數字的兩倍。
如果是,則返回最大元素的索引,否則返回-1。
示例 1:
輸入: nums = [3, 6, 1, 0] 輸出: 1 解釋: 6是最大的整數, 對於數組中的其他整數, 6大於數組中其他元素的兩倍。6的索引是1, 所以我們返回1.
示例 2:
輸入: nums = [1, 2, 3, 4] 輸出: -1 解釋: 4沒有超過3的兩倍大, 所以我們返回 -1.
提示:
nums
的長度範圍在[1, 50]
.- 每個
nums[i]
的整數範圍在[0, 100]
.
public int dominantIndex(int[] nums) {
if(nums.length<1){
return -1;
}
if(nums.length==1){
return 0;
}
int max=nums[0];
int temp=0;
int maxIndex=0;
for(int i=1;i<nums.length;i++){
if(max<=nums[i]){
maxIndex=i;
temp=max;
max=nums[i];
if(max<(2*temp)){
maxIndex=-1;
}
}else{
if(max<(2*nums[i])){
maxIndex=-1;
}
}
}
return maxIndex;
}