码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 453. Minimum Moves to Equal Array Elements

时间:2018-02-10 13:59:31      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:input   来源   blog   exp   example   size   关键词   检查   color   

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]

 

 


题目标签:Math

 

  题目给了我们一个 array,length = n;我们每次能把 n - 1 个 数字 加1 直到 所有数字都一样。让我们返回最少的回合数。
 
  为了使回合数最小,除了最大的数字,剩余数字都 + 1。这样的话需要每次都找到最大的数字,然后把其他数字都加1,之后还要检查是否所有数字都一样。
  我们可以逆向思考,每次只把一个最大的数字 - 1,这样相当于 把其他的数字都 + 1, 直到所有数字一样。
  因为正向思考的方法会遇到 [2, 3, 3] => [3, 4, 3] 这样 最大的数字的值 会继续增长 的情况;而逆向思考的方法却不会,最小的数字的值,是不变的,因为每次都只减一个数字而已。
  这样的话,只要首先找到最小的数字,然后遍历array,把 (每一个数字 减去 min 的值) 累加起来,就是 回合数。
 
 

* for example:                [1,2,3] -> [2,3,3] -> [3,3,4] -> [4,4,4]
* now, think in this way: [1,2,3] -> [1,2,2] -> [1,1,2] -> [1,1,1]

 
 

Java Solution:

Runtime beats 77.57% 

完成日期:06/17/2017

关键词:math

关键点:逆向思考

 1 class Solution 
 2 {
 3     public int minMoves(int[] nums) 
 4     {
 5         int moves = 0;
 6         int min = Integer.MAX_VALUE;
 7         
 8         // find the min value
 9         for(int num : nums)
10             min = Math.min(min, num);
11         
12         
13         // iterate array and calculate the sum of difference between each number and min
14         for(int num : nums)
15             moves += (num - min);
16         
17         return moves;
18     }
19 }

参考资料:http://www.cnblogs.com/grandyang/p/6053827.html

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

LeetCode 453. Minimum Moves to Equal Array Elements

标签:input   来源   blog   exp   example   size   关键词   检查   color   

原文地址:https://www.cnblogs.com/jimmycheng/p/8438484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!