453. Minimum Moves to Equal Array Elements 一次改2个数,变成统一的

[抄题]:

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]

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

逆向思维:n - 1 个数+1是抬高标准,也可以降低标准 一个数-1

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

逆向思维的关键:抬高标准的效果=降低标准

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

Adding 1 to n - 1 elements is the same as subtracting 1 from one element, w.r.t goal of making the elements in the array equal.
So, best way to do this is make all the elements in the array equal to the min element.
sum(array) - n * minimum  n-1元素+1=一个元素-1

[关键模板化代码]:

[其他解法]:

[Follow Up]:

462. Minimum Moves to Equal Array Elements II 还是数学题

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int minMoves(int[] nums) {
        //ini:sort
        Arrays.sort(nums);
        int res = 0, min = nums[0];
        
        //find min
        for (int num : nums) {
            min = Math.min(min, num);    
        }
        
        //add res
        for (int num : nums) {
            res += (num - min);
        }
        
        //return
        return res;
    }
}
View Code

 

posted @ 2018-05-03 10:31  苗妙苗  阅读(134)  评论(0编辑  收藏  举报