Leetcode 453. Minimum Moves to Equal Array Elements 使数组相等 解题报告

来源:互联网 发布:绝地求生4g内存优化 编辑:程序博客网 时间:2024/06/06 09:02

1 解题思想

给了一个数组,长度n,有一些数,现在允许每一次将n-1个数+1
现在问进行了多少步以后,可以使得数组每个元素相等

方法就是找出最小的那个,然后将所有数的和减去最小的那个数乘以数组长度就是了

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:3Explanation:Only three moves are needed (remember each move increments two elements):[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

3 AC解

public class Solution {    public int minMoves(int[] nums) {        if (nums.length == 0) return 0;        int min = nums[0];        int sum = 0;        for (int n : nums) {            min = Math.min(min, n);            sum += n;        }        return sum - nums.length*min;    }}
0 0
原创粉丝点击