【LeetCode】462. Minimum Moves to Equal Array Elements II 解题报告(Python & C++)
作者: 负雪明烛
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++)的更多相关文章
- 【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 ...
- 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 ...
- 462 Minimum Moves to Equal Array Elements II 最少移动次数使数组元素相等 II
给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1. 您可以假设数组的长度最多为10000.例如:输入:[1,2,3]输出:2说明:只有两个动作是必 ...
- 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 ...
- [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 ...
- LeetCode Minimum Moves to Equal Array Elements II
原题链接在这里:https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ 题目: Given a non-empt ...
- 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 ...
- 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 ...
- 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 ...
随机推荐
- eclipse不自动弹出提示的解决办法(eclipse alt+/快捷键失效)
转载:http://yuncode.net/article/a_53bf6888b6f5065 我的问题:在jsp中使用"alt+/"不能够自动导入java包.利用3,4解决问题 ...
- mysql—mysql错误Every derived table must have its own alias解决
Every derived table must have its own alias 这句话的意思是说每个派生出来的表都必须有一个自己的别名. 一般在多表查询时,会出现此错误. 因为,进行嵌套查询的 ...
- 使用Openmp并行化
运行命令:g++ -fopenmp xx.cpp -lgomp -lpthread -o xx.out 用例一: #include <omp.h> #include <stdio.h ...
- abandon, abbreviation
abandon 近/反义词: continue, depart, desert (做动词时读作diˈzəːt), discard, give up, quit, surrender搭配: altoge ...
- 大数据学习day26----hive01----1hive的简介 2 hive的安装(hive的两种连接方式,后台启动,标准输出,错误输出)3. 数据库的基本操作 4. 建表(内部表和外部表的创建以及应用场景,数据导入,学生、分数sql练习)5.分区表 6加载数据的方式
1. hive的简介(具体见文档) Hive是分析处理结构化数据的工具 本质:将hive sql转化成MapReduce程序或者spark程序 Hive处理的数据一般存储在HDFS上,其分析数据底 ...
- 内存管理——array new,array delete
1.array new array new就是申请一个数组空间,所以在delete的时候一定不能忘记在delete前加[] delete加上[]符号以后,就相当于告诉系统"我这里是数组对象, ...
- Nginx流量拷贝
1. 需求 将生产环境的流量拷贝到预上线环境或测试环境,这样做有很多好处,比如: 可以验证功能是否正常,以及服务的性能: 用真实有效的流量请求去验证,又不用造数据,不影响线上正常访问: 这跟灰度发布还 ...
- 【Python】【Basic】【数据类型】基本数据类型
1.数字 int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位系统上,整数的位数为64位,取值范围为-2 ...
- 【编程思想】【设计模式】【结构模式Structural】3-tier
Pyhon版 https://github.com/faif/python-patterns/blob/master/structural/3-tier.py #!/usr/bin/env pytho ...
- JSP 文字乱码、${}引用无效
问题: 代码:<form action="/test/requestPost.do" method="post"> <input type=& ...