453. Minimum Moves to Equal Array Elements | 计算步数

来源:互联网 发布:沉默的螺旋 案例 知乎 编辑:程序博客网 时间:2024/06/05 07:45

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]

思路:

   设步数为m,数组所有数之和为sum,数组最小值为min,数组中值的个数为n

  则 sum + m*(n-1) = (min + m)*n  -> m = sum - n*min.


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


反思:数学问题,应该想到等式方程求解,尤其是有四则运算的。

0 0
原创粉丝点击