leetcode 462. Minimum Moves to Equal Array Elements II

1.题目

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.
一个非空整数组,要求找到最小的移动步数使得整个数组的元素相等。
一次移动可以将一个元素加1或减1

Example:

Input:
[1,2,3]

Output:
2

Explanation:
[1,2,3] => [2,2,3] => [2,2,2]

2.分析

关键在于找到数组的中位数。将每个元素通过多次移动到中位数的总步数是最小的。
找中位数有两种方式:
1)对数组排序,取中间位置的数,复杂度O(nlogn)
2)使用QuickSelect ,复杂度O(n)
3)nth_element,stl部分排序算法。我们只在意整个数组中第k大的数是多少k=length/2

3.代码

QuickSelect

class Solution {
public:
    int quickselect(vector<int> nums, int k, int start, int end) {
        int low = start;
        int high = end;
        int pivot = nums[(end + start) / 2];
        while (low <= high) {
            while (nums[low] < pivot)
                ++low;
            while (nums[high] > pivot)
                --high;
            if (low <= high) {
                swap(nums[low], nums[high]);
                ++low;
                --high;
            }
        }
        if (high > start&&high >= k)
            return quickselect(nums, k, start,high);
        if (low < end&&low <= k)
            return quickselect(nums, k, low, end);
        return nums[k];
    }
    int minMoves2(vector<int>& nums) {
        int sum = 0;
        int median = quickselect(nums, nums.size() / 2, 0, nums.size()-1);
        for (auto n : nums)
            sum += abs(n - median);
        return sum;
    }
};

nth_element

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int sum = 0;
        auto it = nums.begin() + nums.size() / 2;
        nth_element(nums.begin(), it, nums.end());
        int median = *it;
        for (auto n : nums)
            sum += abs(n - median);
        return sum;
    }
};

快排

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int mid = nums[nums.size() / 2];
        int ans = 0;
        for (auto n : nums) 
            ans += abs(n - mid);
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值