首页 > Windows开发 > 详细

LeetCode 453. Minimum Moves to Equal Array Elements C#

时间:2016-12-15 07:31:55      阅读:327      评论:0      收藏:0      [点我收藏+]

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]

Solution:

incrementing n-1 elements by one, means every time need to increment 1 to every number except the maximum. but it‘s hard to implement.

Increment to every nums except max, is as same as decrement 1 on one number until every number equals min number.

 

 1 public class Solution {
 2     public int MinMoves(int[] nums) { 
 3         if(nums.Length==0)
 4         {
 5             return 0;
 6         }
 7         int n = nums.Length;
 8         //Find min value in nums;
 9         int min =nums[0];
10         foreach(int num in nums)
11         {
12             min = Math.Min(min, num);
13         }
14         
15         //calculate the difference of every num from nums and min; ths sum should be the min Moves
16         //add 1 to n-1 is same as minus 1 from the max each time.
17         int moves = 0;
18         foreach(int num in nums)
19         {
20             moves +=(num-min);
21         }
22         return  moves;
23     }
24 }

 

LeetCode 453. Minimum Moves to Equal Array Elements C#

原文:http://www.cnblogs.com/MiaBlog/p/6181805.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!