标签:length blog exce mem except one array tput math
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#
标签:length blog exce mem except one array tput math
原文地址:http://www.cnblogs.com/MiaBlog/p/6181805.html