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.

分析

找到最大元素,遍历比较元素大小即可。

实现

  • scala
1
2
3
4
5
6
7
8
9
10
11

def (nums: Array[Int]): Int = {
val target = nums.sorted.last
val size = nums.length
for ( i <- 0 until size){
if (nums(i) != 0 && target != nums(i) && target/nums(i) < 2 ){
return -1
}
}
nums.indexOf(target)
}

讨论区其他答案

  • java
1
2
3
4
5
6
7
8
9
10
11
12
13
public int (int[] nums) {
int max1 = 0, max2 = 0, idxOfMax1 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max1) {
max2 = max1;
max1 = nums[i];
idxOfMax1 = i;
} else if (nums[i] > max2) {
max2 = nums[i];
}
}
return max1 >= max2 * 2 ? idxOfMax1 : -1;
}
  • go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func (nums []int) int {
if len(nums) == 1 {
return 0
}

index := 1
for i:=0;i<len(nums);i++ {
if nums [i] > nums[index] {
index = i
}
}
for i:= 0;i<len(nums);i++ {
if i != index && nums[i]*2 > nums[index] {
return -1
}
}
return index
}
  • python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def (self, nums):
if len(nums) == 0: return -1

highest = -1
secondHighest = -1
highestIndex = 0

for i,n in enumerate(nums):
if n >= highest:
secondHighest = highest
highest = n
highestIndex = i
elif n > secondHighest:
secondHighest = n

if highest < secondHighest*2:
highestIndex = -1

return highestIndex

参考资料