Leetcode-462. Minimum Moves to Equal Array Elements II

本文介绍了一个简单的算法问题:通过增减元素使数组元素相等所需的最小步数。通过对数组进行排序并找到中位数,可以有效地解决这个问题。文章提供了一个Java实现示例,并解释了其背后的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发优快云,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

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

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]
这个题目挺有意思的,也挺简单的,找到整个数组的中位数,然后求所有数到中位数的距离就行了。 Your runtime beats 26.05% of java submissions.

public class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
	int mid = 0;
	if((nums.length%2) == 0) mid = nums[nums.length /2];
	else mid = nums[(nums.length)/ 2];
	int result = 0;
	for(int item : nums){
		result += Math.abs(mid - item);
	}

	return result;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值