# 747. Largest Number At Least Twice of Others

## 题目

Example 1:

``````Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6是一个最大值，对于其他数字来说，都比他们至少大2倍。而6的位置是1，所以返回1。``````

Example 2:

``````Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4虽然是最大值，但是对于数字3来说，没有大于3倍。因此返回-1。``````

Note:

1. 该数组的长度在1-50之间
2. 对于每一个下标的值，都在0-99之间

## 思路

``````func dominantIndex(nums []int) int {
// find the max
maxIndex := -1
for k, v := range nums {
if v >= nums[maxIndex] {
maxIndex = k
continue
}
}
if maxIndex > -1 {
for k, v := range nums {
if maxIndex == k {
continue
}

if v*2 > nums[maxIndex] {
return -1
}
}
}

return maxIndex
}``````

``````func dominantIndex2(nums []int) int {
if len(nums) < 2 {
return 0
}
largest, second := 0, 1

if nums[largest] < nums[second] {
largest, second = 1, 0
}

for i := 2; i < len(nums); i++ {
if nums[i] > nums[largest] {
largest, second = i, largest
} else if nums[i] > nums[second] {
second = i
}
}

if nums[second]*2 <= nums[largest] {
return largest
}

return -1
}``````