[LeetCode By Go 31]453. Minimum Moves to Equal Array Elements

題目

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

Example:

Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):

[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

解題思路

審題是多么重要,每個操作是將n-1個元素加1,也就是讓另外一個元素減1.想到這里就簡單了,問題變成了累加數(shù)組中各元素與最小值之差

代碼

minMoves.go

package _453_Minimum_Moves2Equal_Array_Elements

func MinMoves(nums []int) int {
    var min int
    min = nums[0]
    length := len(nums)
    for i := 1; i < length; i++ {
        if min > nums[i] {
            min = nums[i]
        }
    }
    if 1 == length {
        return 0
    }
    var sum int
    for i := 0; i < length; i++ {
        sum += nums[i]
    }

    return sum - min * length
}

測試

minMoves_test.go

package _453_Minimum_Moves2Equal_Array_Elements

import "testing"

func TestMinMoves(t *testing.T) {
    var tests = []struct{
        input []int
        output int
    }{
        {
            []int{1, 2, 3}, 3,
        },
        {
            []int{83,86,77,15,93,35,86,92,49,2}, 598,
        },
    }

    for _, test := range tests {
        ret := MinMoves(test.input)

        if ret == test.output {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %d", test.output, ret)
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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