作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/

题目描述

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]

题目大意

题目短的一般都不难。题意是求把一个数组所有的数都弄相等最少需要多少步。一步可以是把某个数字增加1或者把某个数字减少1.

解题方法

方法一:排序

题意已经明确了,把数字调整相等的最小步数,一定是把大数变小,把小数变大,最后都达到其中位数(注意不是均值)。最小化全部/平均距离是中位数的一个显著的性质。

Minimizing the total/average distance is just a prominent property of a median.

可以举例来看:

对于 [1, 5, 6],其均值是4, 中位数是5.

如果把所有的数字都移动到4,需要sum([3,1,2])=6步;

如果把所有的数字都移动到5,需要sum([4,0,1])=5步。

我的理解是,移动到均值容易受到极端值的影响,而移动到中位数则不存在这个问题。具体的数学证明我不会。。当做定理记住好了。

代码:

class Solution(object):
def minMoves2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
median = sorted(nums)[len(nums) / 2]
return sum([abs(num - median) for num in nums])

同样使用排序去做。新学会了~i运算。即求反。python支持负数索引,所以这个运算符很实用啊。

The ~ operator is the same as in C++, so 0, 1, 2, … get turned into -1, -2, -3, … But C++ doesn’t support negative indexing. In Python, index -1 means the last element, index -2 means the next-to-last element, etc.

代码:

class Solution(object):
def minMoves2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return sum([nums[~i] - nums[i] for i in range(len(nums) / 2)])

C++排序解法同样很简单。

排序找中位数的方法如下:

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

方法二:直接找中位数

C++有直接找中位数的函数nth_element(),参数设置成N/2就能把中位数的位置给固定了。这种做法可以不用排序了,速度也更快。

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

日期

2018 年 3 月 4 日
2018 年 12 月 14 日 —— 12月过半,2019就要开始

【LeetCode】462. Minimum Moves to Equal Array Elements II 解题报告(Python & C++)的更多相关文章

  1. 【LeetCode】462. Minimum Moves to Equal Array Elements II

    Given a non-empty integer array, find the minimum number of moves required to make all array element ...

  2. 462. Minimum Moves to Equal Array Elements II

    Given a non-empty integer array, find the minimum number of moves required to make all array element ...

  3. 462 Minimum Moves to Equal Array Elements II 最少移动次数使数组元素相等 II

    给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1. 您可以假设数组的长度最多为10000.例如:输入:[1,2,3]输出:2说明:只有两个动作是必 ...

  4. Leetcode-462 Minimum Moves to Equal Array Elements II

    #462.   Minimum Moves to Equal Array Elements II Given a non-empty integer array, find the minimum n ...

  5. [LeetCode] Minimum Moves to Equal Array Elements II 最少移动次数使数组元素相等之二

    Given a non-empty integer array, find the minimum number of moves required to make all array element ...

  6. LeetCode Minimum Moves to Equal Array Elements II

    原题链接在这里:https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 题目: Given a non-empt ...

  7. LeetCode 453 Minimum Moves to Equal Array Elements

    Problem: Given a non-empty integer array of size n, find the minimum number of moves required to mak ...

  8. LeetCode 453. Minimum Moves to Equal Array Elements C#

    Given a non-empty integer array of size n, find the minimum number of moves required to make all arr ...

  9. 13. leetcode 453. Minimum Moves to Equal Array Elements

    Given a non-empty integer array of size n, find the minimum number of moves required to make all arr ...

随机推荐

  1. vim一键整理代码命令

    vim下写代码超实用代码格式整理命令,仅需四步 ①先使用 gg 命令使光标回到第一行 ②shift+v 进入可视模式 ③shift+g 全选 ④按下  =  即可 混乱的代码格式 四步整理以后 工整又 ...

  2. 【STM32】使用SDIO进行SD卡读写,包含文件管理FatFs(五)-文件管理初步介绍

    其他链接 [STM32]使用SDIO进行SD卡读写,包含文件管理FatFs(一)-初步认识SD卡 [STM32]使用SDIO进行SD卡读写,包含文件管理FatFs(二)-了解SD总线,命令的相关介绍 ...

  3. ORACLE profile含义,修改,新增

    profiles文件是口令和资源限制的配置集合,包括CPU的时间.I/O的使用.空闲时间.连接时间.并发会话数量.密码策略等对于资源的使用profile可以做到控制会话级别或语句调用级别.oracle ...

  4. mysql之join浅析

    1.可以使用join吗?使用join有什么问题呢?-- >超过3个表不使用join,笛卡尔积问题 -->这些问题是怎么造成的呢? 如果可以使用 Index Nested-Loop Join ...

  5. 使用RabbitMQ搭建MQTT服务

    由于近期公司需要搭建一套物联网采集环境,底层设备采用MQTT协议传输数据.服务器环境为linux,考虑到现有环境已经有RabbitMQ环境,Rabbit是基于AMQP协议开发的一套高效的消息传输队列. ...

  6. 一个超简单的Microsoft Edge Extension

    这个比微软官网上的例子简单很多,适合入门.总共4个文件: https://files.cnblogs.com/files/blogs/714801/cet6wordpicker.zip 36KB 1. ...

  7. Git忽略提交规则 .gitignore文件

    在使用Git的过程中,我们喜欢有的文件比如日志,临时文件,编译的中间文件等不要提交到代码仓库,这时就要设置相应的忽略规则,来忽略这些文件的提交.简单来说一个场景:在你使用git add .的时候,遇到 ...

  8. 代码图形统计工具git_stats web

    目录 一.简介 二.安装ruby 三.配置git_stats 四.通过nginx把网页展示出来 一.简介 仓库代码统计工具之一,可以按git提交人.提交次数.修改文件数.代码行数.注释量在时间维度上进 ...

  9. MySQL如何随机筛选25000条数据

    一.SELECT * FROM sheet1 t1 ORDER BY RAND() LIMIT 10000; 二.SELECT * FROM sheet1 AS t1 JOIN (SELECT ROU ...

  10. h5文件下载

    // type1 await getFile(fileUrl).then((res) => { console.log('download',res); let bFile = window.U ...