LeetCode Minimum Moves to Equal Array Elements

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Minimum Moves to Equal Array Elements相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/minimum-moves-to-equal-array-elements/

题目:

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]

题解:

Sort后, nums[0]是最小值, nums[nums.length-1]就是最大值. 若想最小值增加到最大值就需要做nums[nums.length-1] - nums[0] 次move.

之后nums[nums.length-2]就变成了最大值, nums[0], nums[nums.length-1]相等,都是最小值. 若想最小值增加到最大值需要nums[nums.length-2] - nums[0]次move.

以此类推,moves的总数等于(num[nums.length-1] - nums[0]) + (nums[nums.length-2] - nums[0]) + .... + (nums[1] - nums[0]).

Time Complexity: O(nlogn). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int minMoves(int[] nums) {
 3         Arrays.sort(nums);
 4         int move = 0;
 5         for(int i = nums.length-1; i>0; i--){
 6             move += (nums[i]-nums[0]);
 7         }
 8         return move;
 9     }
10 }

DP, sort 之后把原问题拆成小问题. 当nums 的0到i-1位置都已经equal之后,加上新的 i 位置时,只需要做diff = num[i] - nums[i-1]次move就可以全部equal.

当然前面0到i-1的过程中nums[i]早已经加过了,增加的值 等于 前面0到i-1所做的moves总数.

nums[i] += moves成了新的nums[i], nums[i] - nums[i-1]就是这一步需要的move次数.

Time Complexity: O(nlogn). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int minMoves(int[] nums) {
 3         Arrays.sort(nums);
 4         int moves = 0;
 5         for(int i = 1; i<nums.length; i++){
 6             nums[i] += moves;
 7             moves += (nums[i] - nums[i-1]);
 8         }
 9         return moves;
10     }
11 }

数学方法,每次对n-1个element加一 等同于 对 1个element减一。

Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int minMoves(int[] nums) {
 3         int min = Integer.MAX_VALUE;
 4         for(int num : nums){
 5             min = Math.min(min, num);
 6         }
 7         
 8         int moves = 0;
 9         for(int num: nums){
10             moves += (num - min);
11         }
12         return moves;
13     }
14 }

 

以上是关于LeetCode Minimum Moves to Equal Array Elements的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 453. Minimum Moves to Equal Array Elements

[LeetCode] Minimum Moves to Equal Array Elements

Leetcode: Minimum Moves to Equal Array Elements II

[LeetCode] Minimum Moves to Equal Array Elements II

LeetCode 453 Minimum Moves to Equal Array Elements

453. Minimum Moves to Equal Array Elements(LeetCode)