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     }
  • 相关阅读:
    【队列】队列的分类和实现
    【JSP】EL表达式语言
    【JSP】JSP的介绍和基本原理
    【JSP】JSP Action动作标签
    【Servlet】关于RequestDispatcher的原理
    【JSP】JSP指令
    【JSP】JSP中的Java脚本
    【算法】表达式求值--逆波兰算法介绍
    C语言指针详解
    移动架构-MVVM框架
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7701594.html
Copyright © 2011-2022 走看看