最小移動次數 Minimum Moves to Equal Array Elements II

問題:數組

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.ui

You may assume the array's length is at most 10,000.spa

Example:排序

Input:
[1,2,3]
Output:
2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3]  =>  [2,2,3]  =>  [2,2,2]

解決:element

① 先將數組排序,找到中間值,而後兩側的值分別加1或減1變爲中間值時,移動的次數最小。時間複雜度是O(nlogn)rem

class Solution { //13ms
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int mid = nums.length / 2;
        int res = 0;
        for (int n : nums){
            res += Math.abs(n - nums[mid]);
        }
        return res;
    }
}io

相關文章
相關標籤/搜索