Leetcode 453 Minimum Moves to Equal Array Elements
2016-11-29 14:38
711 查看
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:
当向组中的元素增加n-1的时候相当于把最大的元素减1 等到所有的元素都减到和最小元素相等的时候 就是符合题目要求的时候
逆向思维很重要啊
public class Solution {
public int minMoves(int[] nums) {
int sum = 0;
int n= nums.length;
Arrays.sort(nums);
for(int i =0;i<n;i++){
sum+=nums[i]-nums[0];
}
return sum;
}
}
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-1的时候相当于把最大的元素减1 等到所有的元素都减到和最小元素相等的时候 就是符合题目要求的时候
逆向思维很重要啊
public class Solution {
public int minMoves(int[] nums) {
int sum = 0;
int n= nums.length;
Arrays.sort(nums);
for(int i =0;i<n;i++){
sum+=nums[i]-nums[0];
}
return sum;
}
}
相关文章推荐
- leetcode-453-Minimum Moves to Equal Array Elements
- leetcode 453 Minimum Moves to Equal Array Elements
- leetcode 453 Minimum Moves to Equal Array Elements C++
- [Leetcode] 453 Minimum Moves to Equal Array Elements
- LeetCode - 453/462 - Minimum Moves to Equal Array Elements
- Leetcode-453 Minimum Moves to Equal Array Elements
- LeetCode 453 Minimum Moves to Equal Array Elements
- Leetcode 453 Minimum Moves to Equal Array Elements
- [leetcode 453]Minimum Moves to Equal Array Elements
- [return sum(nums)-min(nums)*len(nums)leetcode453】 Minimum Moves to Equal Array Elements
- leetcode Minimum Moves to Equal Array Elements 453
- Leetcode 462 Minimum Moves to Equal Array Elements II
- Leetcode Minimum Moves to Equal Array Elements
- LeetCode: Minimum Moves to Equal Array Elements
- [leetcode][462] Minimum Moves to Equal Array Elements II
- leetcode_Minimum Moves to Equal Array Elements
- Leetcode 之 Minimum Moves to Equal Array Elements II
- LeetCode 462 Minimum Moves to Equal Array Elements II (中位数)
- LeetCode Minimum Moves to Equal Array Elements
- LeetCode "Minimum Moves to Equal Array Elements"