zoukankan      html  css  js  c++  java
  • LeetCode 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]
    

    题目标签: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/

  • 相关阅读:
    Linux | Ubuntu 生成二维码实例
    Ubuntu 添加wine安装程序的快捷方式
    mysql 中文 排序
    Received disconnect from **.**).***.*** port 22:2: Too many authentication failures 解决办法
    php 数组与URL相互转换
    ssh `快捷键` 快速链接服务器
    使用ssh生成密钥并保存在不同的文件(ubuntu)
    H5移动端调试 weinre
    简单的 图片下载 php
    linux 系统生成二维码
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/8438484.html
Copyright © 2011-2022 走看看