zoukankan      html  css  js  c++  java
  • leetcode453-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
    • n所有元素相等
    • [1,2,3]

    问题分析

    • 第一遍:将所有的n-1个元素加一等价于将另一个元素减一,故而最小步骤即为所有元素与最小值元素之差的和。
      class Solution {
          public int minMoves(int[] nums) {
              if(nums.length <= 1) return 0;
              int min = Integer.MAX_VALUE;
              for(int i = 0; i < nums.length; i++){
                  if(nums[i] < min){
                      min = nums[i];
                  }
              }
              
              int res = 0;
              for(int i = 0; i < nums.length; i++){
                  res += nums[i] - min;
              }
              
              return res;
          }
      }

    • class Solution {
          public int minMoves(int[] nums) {
              if(nums.length <= 1) return 0;
              int min = Integer.MAX_VALUE;
              int sum = 0;
              for(int i = 0; i < nums.length; i++){
                  if(nums[i] < min){
                      min = nums[i];
                  }
                  sum += nums[i];
              }
              
              return sum - nums.length * min;
          }
      }

  • 相关阅读:
    蜂窝网格的坐标以及寻路
    unity3d 第三人称视角的人物移动以及相机控制
    基本HTML结构
    平衡二叉树
    STL基础复习
    递归
    unity 傅老师学习
    blender基础操作
    最小生成树
    最短路径
  • 原文地址:https://www.cnblogs.com/clairexxx/p/10534964.html
Copyright © 2011-2022 走看看