LeetCode 453. 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]

题解:

Think on the other way, increasing n - 1 elements == decreasing 1 element.

Decrease all num to min(nums).

Time Complexity: O(n). n = nums.length.

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 }

Could be one pass.

Time Complexity: O(n).

Space: O(1).

AC Java:

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

跟上Minimum Moves to Equal Array Elements II.

posted @ 2017-01-07 09:22  Dylan_Java_NYC  阅读(331)  评论(0编辑  收藏  举报