Leetcode Note: Go - Largest Number at Least Twice of Others

Largest Number At Least Twice of Others - LeetCode
https://leetcode.com/problems/largest-number-at-least-twice-of-others/

  • Go 言語で取り組んだメモ

所感

  • int 配列 nums が与えられる
  • 配列内の最大要素が、他要素の2倍以上か判断
  • 最大要素のインデックスか -1 を return する

回答

Golang 0ms - LeetCode Discuss
https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/926129/Golang-0ms

func dominantIndex(nums []int) int {
	var maxv, idx int
	for i, v := range nums {
		if maxv < v {
			maxv, idx = v, i
		}
	}

	for _, v := range nums {
		if v != maxv && v*2 > maxv {
			return -1
		}
	}

	return idx
}