LeetCode:453. Minimum Moves to Equal Array Elements

本文介绍了解决LeetCode上编号为453的问题——如何用最少的步数使数组元素相等的方法。通过寻找数组中的最小值并计算所有元素与该最小值之间的差值总和来得出答案。
 1 package Today;
 2 //LeetCode:453. Minimum Moves to Equal Array Elements
 3 /*
 4 Given a non-empty integer array of size n, find the minimum number of moves required to make all array 
 5 elements equal, where a move is incrementing n - 1 elements by 1.
 6 
 7 Example:
 8 Input:
 9 [1,2,3]
10 Output:
11 3
12 Explanation:
13 Only three moves are needed (remember each move increments two elements):
14 [1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
15 */
16 public class minMoves453 {
17     public static int minMoves(int[] nums) {
18         int min=nums[0];
19         int sum=0;
20         for(int i=1;i<nums.length;i++){
21             if(nums[i]<min)
22                 min=nums[i];
23         }
24         for(int i=0;i<nums.length;i++){
25             sum+=nums[i]-min;
26         }
27         return sum;
28     }
29     public static void main(String[] args) {
30         // TODO Auto-generated method stub
31         int[] nums={1,2,3};
32         int[] nums2={1,2,4,6};
33         System.out.println(minMoves(nums));
34         System.out.println(minMoves(nums2));
35     }
36 
37 }

 

转载于:https://www.cnblogs.com/luluqiao/p/6369657.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值