zoukankan      html  css  js  c++  java
  • 453. Minimum Moves to Equal Array Elements 一次改2个数,变成统一的

    [抄题]:

    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]

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [一句话思路]:

    逆向思维:n - 1 个数+1是抬高标准,也可以降低标准 一个数-1

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    逆向思维的关键:抬高标准的效果=降低标准

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    Adding 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  n-1元素+1=一个元素-1

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    462. Minimum Moves to Equal Array Elements II 还是数学题

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int minMoves(int[] nums) {
            //ini:sort
            Arrays.sort(nums);
            int res = 0, min = nums[0];
            
            //find min
            for (int num : nums) {
                min = Math.min(min, num);    
            }
            
            //add res
            for (int num : nums) {
                res += (num - min);
            }
            
            //return
            return res;
        }
    }
    View Code
  • 相关阅读:
    Android画图最基本的三个对象(Color,Paint,Canvas)
    搭建Android开发环境之旅
    对象序列化与反序列化
    JUnit 3.8 演示递归删除文件目录的 测试类程序 .
    JUnit 3.8 让所有测试程序 实现 复合的测试(TestSuite)
    JUnit 3.8 通过反射测试私有方法
    Java NIO
    Java泛型 类型变量的限定
    组织领导层在信息化建设中须要解决的问题
    bootstrap之鼠标操作
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8984147.html
Copyright © 2011-2022 走看看