zoukankan      html  css  js  c++  java
  • 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-1个数字+1(n为数组长度)问最少几次使得数组中的每个数据相等?

    思路:

    1.既然询问最少次数,我们观察例子中如何达到最少:每次选择的n-1个均避开当前数组中最大值。

    2.如果在代码中将数组变换的中间结果列出,算法复杂度肯定较大,所以我们逆向思考:目的都是数组中每个数据彼此相等,那么每次使得其中1个数据-1,最终达到目的 与题意的moves相同。

    3. 2中的思路可以转换为数组中的每个非最小值到最小值的次数,则moves += min[i] - min

    1     public int minMoves(int[] nums) {
    2         int mn = Integer.MAX_VALUE, res = 0;
    3         for (int num : nums) mn = Math.min(mn, num);
    4         for (int num : nums) res += num - mn;
    5         return res;        
    6     }
  • 相关阅读:
    Linux下redis的安装
    python 文档
    Asp.net 高性能 Sqlite ORM 框架之 sqliteSugar
    程序整理网
    第十章:更多
    第九章:高级应用举例
    第八章:简单应用举例(2)
    第八章:简单应用举例(1)
    第七章:Mapping插件
    第六章:加载或保存JSON数据
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7701594.html
Copyright © 2011-2022 走看看