GuilinDev

Lc0462

05 August 2008

462 Minimum Moves to Equal Array Elements II

给一个array,变化里面的元素使其每个元素都相等,求变化最小的次数

排序后类似meeting rooms,two pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int i = 0, j = nums.length-1;
        int count = 0;
        while(i < j){
            count += nums[j]-nums[i];
            i++;
            j--;
        }
        return count;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int minMoves2 (int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        int n = nums.length;
        Arrays.sort (nums);
        int mid = n/2;
        int count = 0;
        for (int i = 0; i < n; i++)
            count += (Math.abs (nums [i] - nums [mid]));
        return count;
    }
}