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

解題思路

要求一個數(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)
        }
    }
}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容