[LeetCode By Go 747] Easy, Array, 747. 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.

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].

解题思路

要求一个数组中的最大值是否是其他所有值的最少两倍,如果是则返回最大值的下标,否则返回-1.
先求出最大值,然后再次遍历数组,判断最大值max是否小于其他值的两倍,如果是则返回-1;如果可以遍历完,则返回最大值的下标。

代码

请参考我的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)
        }
    }
}


    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/38267bb3efa9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞