Leetcode - Divide Array in Sets of K Consecutive Numbers
Leetcode - Happy Number

Leetcode - Largest Number At Least Twice of Others

violet posted @ Apr 02, 2020 10:00:41 AM in 算法 with tags Algorithm Golang array , 239 阅读

https://leetcode.com/problems/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.

 

func dominantIndex(nums []int) int {
    maxNum := math.MinInt32
    maxIndex := -1
    for i, n := range nums {
        if n > maxNum {
            maxNum = n
            maxIndex = i
        }
    }
    for i, n := range nums {
        if i != maxIndex && maxNum < n * 2 {
            return -1
        }
    }
    return maxIndex
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter