LeetCode 至少是其他數字兩倍的最大數 [簡單]
在一個給定的數組nums中,總是存在一個最大元素 。
查找數組中的最大元素是否至少是數組中每個其他數字的兩倍。
如果是,則返回最大元素的索引,否則返回-1。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others
示例 1:
輸入: nums = [3, 6, 1, 0]
輸出: 1
解釋: 6是最大的整數, 對于數組中的其他整數,
6大于數組中其他元素的兩倍。6的索引是1, 所以我們返回1.
示例 2:
輸入: nums = [1, 2, 3, 4]
輸出: -1
解釋: 4沒有超過3的兩倍大, 所以我們返回 -1.
題目分析
解法1
只要找到最大的兩個數字即可
代碼實現
public class TwiceTheMaximum {
public static void main(String[] args) {
int[] nums = {3, 6, 1, 0};
int[] nums2 = {1, 2, 3, 4};
int index = dominantIndex(nums);
System.out.println(index);
System.out.println(dominantIndex(nums2));
}
public static int dominantIndex(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int tempIndex = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= max1) {
max1 = nums[i];
tempIndex = i;
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= max2 && nums[i] < max1) {
max2 = nums[i];
}
}
if (max1 < max2 * 2) {
return -1;
} else {
return tempIndex;
}
}
}