文章目录
  1. 1. 题意
  2. 2. 题意翻译
  3. 3. 代码参考

题意

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.

题意翻译

这个题的意思是说给定一个整数数组,让你找到这个数组里的最大值max和第二大secondMax的值,然后判断max是否比secondMax的二倍还要大。这里的工作是要找到第一大的数和第二大的数,然后保留第一大的数的下标。可以通过遍历一遍数组然后用三个变量分别记录最大值,第二大值,和第一大的数的下标。

代码参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public int dominantIndex(int[] nums) {
if (nums.length == 0 || nums == null){
return 0;
}
if (nums.length == 1){
return 0;
}
int maxValue = Integer.MIN_VALUE + 1;
int SecondMaxValue = Integer.MIN_VALUE;
int index = 0;
for (int i=0 ; i<nums.length ; i++){
if (nums[i] > maxValue){
SecondMaxValue = maxValue;
maxValue = nums[i];
index = i;
}else if (nums[i] != maxValue && nums[i] > SecondMaxValue){
SecondMaxValue = nums[i];
}
}
if (maxValue >= 2*SecondMaxValue){
return index;
}
return -1;
}
}
文章目录
  1. 1. 题意
  2. 2. 题意翻译
  3. 3. 代码参考