使數組值相等的最小步數 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.ui

Example:spa

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]

解決:three

① 其實就是數學問題, 所有n-1個值加1就是一個值減1,14mselement

public class Solution {
    public int minMoves(int[] nums) {
        if (nums.length == 0) return 0;
        int min = nums[0];
        for (int n : nums) min = Math.min(min, n);
        int res = 0;
        for (int n : nums) res += n - min;
        return res;
    }
}
② 公式 sum(array)- n * min(array)。11msrem

咱們假設sum爲移動前全部數組值之和,minNum是數組中的最小值,n是數組的長度,通過m次移動n-1個小於最大值的數,咱們獲得全部數組值相等爲x.能夠獲得以下公式:
sum + m * (n - 1) = x * n
另外還有:x = minNum + m
最後,咱們能夠獲得:sum - minNum * n = m
數學

public class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE;
        int sum = 0;
        for(int i = 0 ; i < nums.length ; i ++){
            min = Math.min(min, nums[i]);
            sum += nums[i];
        }
        return sum - nums.length * min;
    }
}io

相關文章
相關標籤/搜索