題目
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].
解題思路
要求一個數(shù)組中的最大值是否是其他所有值的最少兩倍,如果是則返回最大值的下標(biāo),否則返回-1.
先求出最大值,然后再次遍歷數(shù)組,判斷最大值max是否小于其他值的兩倍,如果是則返回-1;如果可以遍歷完,則返回最大值的下標(biāo)。
代碼
請參考我的GitHub獲得更多使用go解答LeetCode的代碼
dominantIndex.go
package _747_Largest_Number
func dominantIndex(nums []int) int {
length := len(nums)
if 1 == length {
return 0
}
var ret int
var max int
max = nums[0]
for i := 1; i < length; i++ {
v := nums[i]
if v > max {
max = v
ret = i
}
}
for _, v := range nums {
if v == max {
continue
}
if max < v*2 {
return -1
}
}
return ret
}
測試
dominantIndex_test.go
package _747_Largest_Number
import (
"testing"
)
type Input struct {
nums []int
expected int
}
func TestDominatIndex(t *testing.T) {
var inputs = []Input{
Input{
nums: []int{0, 0, 2, 3},
expected: -1,
},
}
for _, input := range inputs {
ret := dominantIndex(input.nums)
if ret == input.expected {
t.Logf("Pass")
} else {
t.Errorf("Fail, expect %v, get %v\n", input.expected, ret)
}
}
}