LeetCode-462. Minimum Moves to Equal Array Elements II [C++][Java]

该博客介绍了如何解决LeetCode上的462题,即找到使得数组所有元素相等所需的最小移动次数。解题思路包括使用C++和Java两种编程语言实现,通过找到中位数并计算每个元素与中位数的差值来得出总移动次数。
摘要由CSDN通过智能技术生成

LeetCode-462. Minimum Moves to Equal Array Elements IIicon-default.png?t=M276https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/

题目描述

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment or decrement an element of the array by 1.

Test cases are designed so that the answer will fit in a 32-bit integer.

Example 1:

Input: nums = [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]

Example 2:

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

Constraints:

  • n == nums.length
  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

解题思路

【C++】

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int move = 0;
        int median = findKthSmallest(nums, nums.size() / 2);
        for(int num : nums) move += abs(num - median);
        return move;
    }

    int findKthSmallest(vector<int>& nums, int k) {
        int l = 0, h = nums.size() - 1;
        while (l < h) {
            int j = partition(nums, l, h);
            if(j == k) break;
            if(j < k) l = j + 1;
            else h = j - 1;
        }
        return nums[k];
    }

    int partition(vector<int>& nums, int l, int h) {
        int i = l, j = h + 1;
        while(true) {
            while(nums[++i] < nums[l] && i < h) ;
            while(nums[--j] > nums[l] && j > l) ;
            if(i >= j) break;
            swap(nums, i, j);
        }
        swap(nums, l, j);
        return j;
    }

    void swap(vector<int>& nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

用已有sort函数

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        int res = 0;
        for (auto i : nums) {res += abs(i-nums[n/2]);}
        return res;
    }
};

【Java】

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值