LeetCode | 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,使得最後所有的數相等。容易想到,n-1個元素+1時,不會對最大數進行+1操作,否則就永遠不可能到所有數相等的時候了。而對n-1個非最大數加1,可以等效爲每次對最大數減1,直到所有數相等,而相等時容易知道,所有數均爲數組最小數。故題目又可等效爲,數組中所有元素與最小數之差的和,代碼如下:

public class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE;
        for(int n : nums) min = Math.min(n, min);
        int moves = 0;
        for(int n : nums) moves += n - min;
        return moves;
    }
}

容易觀察到,每次求各個數最小值之和,都要減掉最小數,所以可以將代碼簡化成數組所有數相加,減掉n個最小數,代碼如下:

public class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE;
        for(int n : nums) min = Math.min(n, min);
        int moves = 0;
        for(int n : nums) moves += n;
        return moves - nums.length * min;
    }
}

在上面的代碼中,找最小數並沒有採用sort之後取第一個數的作法,這是因爲其算法複雜度爲O(nlogn) ,而直接調用API的min來找,則複雜度僅爲O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章