当前位置:网站首页>力扣解法汇总462-最少移动次数使数组元素相等 II
力扣解法汇总462-最少移动次数使数组元素相等 II
2022-06-12 02:03:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:力扣
描述:
给你一个长度为 n 的整数数组 nums ,返回使所有数组元素相等需要的最少移动数。
在一步操作中,你可以使数组中的一个元素加 1 或者减 1 。
示例 1:
输入:nums = [1,2,3]
输出:2
解释:
只需要两步操作(每步操作指南使一个元素加 1 或减 1):
[1,2,3] => [2,2,3] => [2,2,2]
示例 2:
输入:nums = [1,10,2,9]
输出:16
提示:
n == nums.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-moves-to-equal-array-elements-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
* 解题思路: * 该题中,中位数为基准值一定是最少移动次数。 * 所以先对nums进行排序,求其他数和中位数的差即可。
代码:
public class Solution462 {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int middle = nums[nums.length / 2];
int count = 0;
for (int i : nums) {
count += Math.abs(middle - i);
}
return count;
}
}边栏推荐
- Summary of concrete (ground + wall) + Mountain crack data set (classification and target detection)
- Graphic data analysis | business cognition and data exploration
- How WPS inserts a directory and the operating steps for quickly inserting a directory
- 关于vagrant up的一个终结之谜
- 螺旋矩阵(技巧)
- Bracket generation (backtracking)
- 联调这夜,我把同事打了...
- leetcode:6. Zigzag transformation
- In Net platform using reflectiondynamicobject to optimize reflection calling code
- UE4\UE5触摸屏touch事件:单指、双指
猜你喜欢

MySQL advanced knowledge points

Glfwpollevents() program crash

Does the virtual host have independent IP

Graphic data analysis | business cognition and data exploration

Graphic data analysis | data cleaning and pretreatment

Pyinstaller packaging Exe (detailed tutorial)

ACL2022 | DCSR:一种面向开放域段落检索的句子感知的对比学习方法

The release of star ring kundb 2.2 provides a new choice for business systems with high concurrent transactions and queries

Software engineering - system flow chart

如何让杀毒软件停止屏蔽某个网页?以GDATA为例
随机推荐
打包一个包含手表端应用的手机端APK应用—Ticwear
Bracket generation (backtracking)
C language programming classic games - minesweeping
Four schemes for redis to implement message queue
Make ads more relevant by searching for additional information about ads
ozzanimation-基於sse的動作系統
Educational knowledge and ability test questions of primary and secondary school educational endowment examination in the second half of 2019 (middle school) - subjective questions
LeetCode LCP 07. Deliver information
SQL calculates KS, AUC, IV, psi and other risk control model indicators
PHP builds a high-performance API architecture based on sw-x framework (III)
竞价广告每次点击出价多少钱是固定的吗?
leetcodeSQL:612. Nearest distance on plane
如何让杀毒软件停止屏蔽某个网页?以GDATA为例
关于vagrant up的一个终结之谜
Graphic data analysis | data cleaning and pretreatment
[adjustment] in 2022, the Key Laboratory of laser life sciences of the Ministry of education of South China Normal University enrolled adjustment students in optics, electronic information, biomedicin
如何最大化的利用各种匹配方式? ——Google SEM
CVPR2022 | iFS-RCNN:一种增量小样本实例分割器
Operating mechanism of Google ads bidding
Unit tests in golang