LeetCode每日一题: 最小移动次数使数组元素相等(No.453)

栏目: 编程工具 · 发布时间: 5年前

给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。
复制代码

示例:

输入:
[1,2,3]

输出:
3

解释:
只需要3次移动(注意每次移动会增加两个元素的值):
[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
复制代码

思考:

这道题可以反过来想,按题意将n-1个元素加1,其实可以当做给剩下的那个数减1。
加一:[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
减一:[1,2,3]  =>  [1,2,2]  =>  [1,1,2]  =>  [1,1,1]
所以先求出最小的元素,在求出所有元素与最小元素的差值的和,即为最小移动次数。
复制代码

实现:

class Solution {
public int minMoves(int[] nums) {
    int min = nums[0];
    int count = 0;
    for(int i = 0;i<nums.length;i++){
        min = Math.min(nums[i],min);
    }
    for(int i = 0;i<nums.length;i++){
        count += nums[i] - min;
    }
    return count;
}
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Uberland

Uberland

Alex Rosenblat / University of California Press / 2018-11-19 / GBP 21.00

Silicon Valley technology is transforming the way we work, and Uber is leading the charge. An American startup that promised to deliver entrepreneurship for the masses through its technology, Uber ins......一起来看看 《Uberland》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具