"Leetcode" Minimum moves to Equal Array Elements problem-solving report
tags (space-delimited): Leetcode
[Leetcode]
Https://leetcode.com/problems/minimum-moves-to-equal-array-elements/Difficulty:Easy Question
Given a non-empty integer array of size n, find the minimum number of moves required to do all array elements equal, whe Re a move are 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]
Ways
Method One:
I use the direct method, each time to sort the array, and then the first n-1 elements + +, and then sorted, know that the elements are equal.
According to the test case, this method should be right, but the method time is exceeded.
public class Solution {public
int minmoves (int[] nums) {
int count=0;
Arrays.sort (nums);
while (Nums[0]!= nums[nums.length-1]) {for
(int i=0; i<nums.length-1; i++) {
nums[i]++;
}
Arrays.sort (nums);
count++;
}
return count;
}
}
Method Two:
After reading the answer to the high votes, only understand that the smallest of the n-1 elements are + + equivalent to the largest element-;
Our goal is to make all the elements equal, that is, each time the largest element-1 until all elements are equal to the smallest element.
So the total number of operations equals the difference between all elements and the smallest elements: sum (array)-N * Minimum
public class Solution {public
int minmoves (int[] nums) {
int count=0;
int min=nums[0];
for (int num:nums) {
min=math.min (min,num);
}
for (int num:nums) {
count + = num-min;
}
return count;
}
}
Ac:14 ms
Method Three:
Inspired by the above ideas, reflective method, no need for each cycle are ordered, according to the strategy of subtraction, after sorting, the first element is the smallest element, and then find the other elements and the difference between the smallest elements.
The time complexity of the sort algorithm is O (Nlog (n))
public class Solution {public
int minmoves (int[] nums) {
int count=0;
Arrays.sort (nums);
for (int num:nums) {
count + = Num-nums[0];
}
return count;
}
}
Ac:53 ms
The answer to the website is very good, very comprehensive and with the video. Praise. https://leetcode.com/articles/minimum-moves-to-equal-array-elements/ Date
January 7, 2017