453. Minimum Moves to Equal Array Elements

本文针对一个特定的数组操作问题提供了解决方案。该问题是:如何通过增量操作使数组中的所有元素相等,即每次选择n-1个元素各加1,直至所有元素相等,并求出最少的操作次数。文章中提出了一种逆向思维的方法来简化问题,并给出了具体的实现代码。

 

Given anon-emptyinteger array of sizen, find the minimum number of moves required to make all array elements equal, where a move is incrementingn- 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操作,使得这个数组的所有元素相同。求操作的最小次数。
看到题目我就立马拿起了笔,找了个例子开始各种的尝试,希望能够找到某种规律,结果一个简单的小例子就需要推导半天。。。=.=!,看了下大神是怎么做的。网上给出的思路是换位思考。每次对n-1个数字+1,那不等价于每次对1个数字-1么。给出答案
class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE;
        for(int num:nums) min = Math.min(num,min);
        int result = 0;
        for(int num:nums) result += (num-min);
        return result;
    }
}

 

 
 
 
 

转载于:https://www.cnblogs.com/wxshi/p/7598322.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值