当前位置:网站首页>Force deduction solution summary 462- minimum number of moves to make array elements equal II

Force deduction solution summary 462- minimum number of moves to make array elements equal II

2022-06-12 02:08:00 Lost summer

  Directory links :

Force buckle programming problem - The solution sums up _ Share + Record -CSDN Blog

GitHub Synchronous question brushing items :

https://github.com/September26/java-algorithms

Original link : Power button


describe :

Give you a length of n Array of integers for nums , Returns the minimum number of moves required to make all array elements equal .

In one step , You can add... To an element in the array 1 Or minus 1 .

Example 1:

Input :nums = [1,2,3]
Output :2
explain :
Just two steps ( The instructions for each step add... To an element 1 Or minus 1):
[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
Example 2:

Input :nums = [1,10,2,9]
Output :16
 

Tips :

n == nums.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109

source : Power button (LeetCode)
link :https://leetcode.cn/problems/minimum-moves-to-equal-array-elements-ii
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Their thinking :

*  Their thinking :
*  In this question , The median is the reference value, which must be the minimum number of moves .
*  So first nums Sort , Find the difference between other numbers and the median .

Code :

public class Solution462 {

    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int middle = nums[nums.length / 2];
        int count = 0;
        for (int i : nums) {
            count += Math.abs(middle - i);
        }
        return count;

    }
}

原网站

版权声明
本文为[Lost summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120202543083.html