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]

    最小移动次数使数组元素相等。

    这道题给的是一个数组,里面的数字不尽相同。假设数组里有N个数字,有一个最大数字max。找到让数组所有元素相等的最小移动次数。每次移动将会使 N - 1 个元素增加 1。

    这道题不难,首先讲一下直观的思路。首先找出数组中最大的数字这不难,然后直接将剩下的数字每次+1。同时,还需要在每一轮+1之后再次检查最大值是否有变化。这样做虽然直观但是会超时。

    一个巧妙的思路是,给n - 1个数字加1,效果等同于给那个未被选中的数字减1。所以问题也可转化为,将所有数字都减小到最小值。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int minMoves(int[] nums) {
     3         int min = Integer.MAX_VALUE;
     4         int res = 0;
     5         for (int num : nums) {
     6             min = Math.min(min, num);
     7         }
     8         for (int num : nums) {
     9             res += num - min;
    10         }
    11         return res;
    12     }
    13 }

    LeetCode 题目总结

  • 相关阅读:
    C#调用C++ ---参数传递
    Retained Mode Versus Immediate Mode
    mind map in latex
    vk example
    基本环境
    [转]ld 和 ld.gold 和 ld.bfd
    [转] c++11 int&& 右值引用
    [转] c++11列表初始化
    [转] c++ const, volatile, mutable用法
    [转] c++11 模板元编程
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13611537.html
Copyright © 2011-2022 走看看