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
  • 相关阅读:
    Linq 中 表连接查询
    Html Div 拖拽
    持续集成:TestNG中case之间的关系
    测试技术培训:如何测试磁盘写的速度
    POPTEST 测试开发 免费培训课程报名
    接上文 下面是一段示例代码
    老李分享:android手机测试之适配(1)
    (转)POPTEST创始人李爱然:谢谢,帮助我的朋友!!!!
    性能调优之SQL优化
    大数据测试之Hadoop的基本概念
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8984147.html
Copyright © 2011-2022 走看看