GO.至少是其他数字两倍的最大数
题目: 给你一个整数数组 nums ,其中总是存在 唯一的 一个最大整数 。
请你找出数组中的最大元素并检查它是否 至少是数组中每个其他数字的两倍 。如果是,则返回 最大元素的下标 ,否则返回 -1 。
You are given an integer array nums where the largest integer is unique. Determine 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, or return -1 otherwise.
示例 1:
输入:nums = [3,6,1,0]
输出:1
解释:6 是最大的整数,对于数组中的其他整数,6 大于数组中其他元素的两倍。6 的下标是 1 ,所以返回 1 。
示例 2:
输入:nums = [1,2,3,4]
输出:-1
解释:4 没有超过 3 的两倍大,所以返回 -1 。
示例 3:
输入:nums = [1]
输出:0
解释:因为不存在其他数字,所以认为现有数字 1 至少是其他数字的两倍。
解题思路: 1.遍历数据并找出最大数和最大数下标和次大数 2.最大数大于或等于次大数的两倍时返回最大数的下标 3.否则返回-1
func dominantIndex(nums []int) int {
if len(nums) == 1 {
return 0
}
max1,max2,index := -1,-1,0
for i,v:=range nums {
if v > max1 {
max2,ma1,index := max1,v,i
} else if v > max2 {
max2 = v
}
}
if max1 >= max2*2 {
return index
}
return -1
}