453. Minimum Moves to Equal Array Elements

来源:互联网 发布:知己知皮下一句是什么 编辑:程序博客网 时间:2024/05/23 11:51

Given a non-empty integerarray of size n, find the minimum number of moves required to make all arrayelements 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的非空整数数组,找到使所有数组元素相等所需的最小移动数,其中移动将n-1个元素递增1

    例:

    输入:[1,2,3]    输出:3

    说明:只需要三个动作(记住每个动作增加两个元素):[1,2,3] => [2,3,3] =>[3,4,3] => [4,4,4]

    题目意思是将一组数的n-1个数每次都加1,实际上就是每次让最大的数减1,最后使数组的值全部和最小值相等。计算总的次数。代码如下:

public class Solution {

    public int minMoves(int[] nums) {

        int min=nums[0],result=0;

           for(int i=1;i<nums.length;i++){

                 if(nums[i]>min){

                      result+=(nums[i]-min);

                 }else{

                      result+=(min-nums[i])*i;

                      min=nums[i];

                 }

           }

           return result;

    }

}

0 0
原创粉丝点击