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]

    Subscribe to see which companies asked this question

    【题目分析】

    给定一个长度为n的非空的整数数组,每次把数组中的n-1元素加1,求出使得数组中元素都相同所需要的最少的操作次数。

    【思路】

    Add 1 to n - 1 elements is the same as subtracting 1 from one element, w.r.t goal of making the elements in the array equal.
    So, best way to do this is make all the elements in the array equal to the min element.
    sum(array) - n * minimum

    这个想法真的是醉了,脑子不够用啊

    代码如下:

     1 public class Solution {
     2     public int minMoves(int[] nums) {
     3         if (nums.length == 0) return 0;
     4         int min = nums[0];
     5         for (int n : nums) min = Math.min(min, n);
     6         int res = 0;
     7         for (int n : nums) res += n - min;
     8         return res;
     9     }
    10 }
  • 相关阅读:
    文件
    模块
    异常
    抽象
    条件,循环
    centos6.4 64位下安装nfs文件共享系统
    YUM安装删除软件
    apache常用的两种工作模式 prefork和worker
    shell不打印
    APACHE安装配置说明
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6118691.html
Copyright © 2011-2022 走看看