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

leetcoode刷题 453. Minimum Moves to Equal Array Elements

时间:2018-09-15 00:37:19      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:注意   分享图片   OLE   exp   题目   span   size   als   xpl   

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



中文版:给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。

示例:

输入:
[1,2,3]

输出:
3

解释:
只需要3次移动(注意每次移动会增加两个元素的值):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]





解答1:正常思维:为了达到题目要求我们可以每次都给数组中除最大的数+1,直到所有的数都相等为止。但是这种做法复杂度太高了。
class Solution {
    public int minMoves(int[] nums) {
        int cnt=0;
        while (true){
            boolean flag=true;
            int indexOfMax=0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i]>nums[indexOfMax]) indexOfMax=i;
                if (nums[i]!=nums[i-1]) flag=false;
            }

            if (flag==false){
                cnt++;
                for (int i = 0; i <nums.length ; i++) {
                    if (i!=indexOfMax) nums[i]++;
                }
            }else {
                break;
            }
        }
        //System.out.println(c);
        return cnt;
    }
}

 这种解答结果:技术分享图片

 


解答2:逆向思维,每次给最大的数之外的数字+1,可以看作是最大的数——1,一直减到所有的数都等于数组中最小的数为止,
    这样我们只需要统计数组中最小的数字是多少以及数组中所有数字之和为多少就可以解决问题,复杂度为O(n)。
 1 class Solution {
 2     public int minMoves(int[] nums) {
 3        int min=Integer.MAX_VALUE;
 4         int sum=0;
 5         for (int i = 0; i < nums.length; i++) {
 6             min=Math.min(nums[i],min);
 7             sum+=nums[i];
 8         }
 9 
10         return sum-min*nums.length;
11     }
12 }

运行结果:技术分享图片

 

leetcoode刷题 453. Minimum Moves to Equal Array Elements

标签:注意   分享图片   OLE   exp   题目   span   size   als   xpl   

原文地址:https://www.cnblogs.com/ming-jia/p/9649583.html

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