作者: 负雪明烛
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. web性能测试工具——http_load

    http_load是一款基于Linux平台的web服务器性能测试工具,用于测试web服务器的吞吐量与负载,web页面的性能. http_load是基于linux.unix平台的一种性能测工具 它以并行 ...

  2. Netty | 第1章 Java NIO 网络编程《Netty In Action》

    目录 前言 1. Java 网络编程 1.1 Javs NIO 基本介绍 1.2 缓冲区 Buffer 1.2 通道 Channel 1.3 选择器 Selector 1.4 NIO 非阻塞网络编程原 ...

  3. A Child's History of England.6

    It was a British Prince named Vortigern who took this resolution, and who made a treaty of friendshi ...

  4. 【STM8】添加头文件、加入库函数

    下面顺便放上STM8L15x-16x-05x的固件库,以及固件库里没有的<stm8l15x_conf.h> 链接打开后,还会发现另外两个文件夹,<src><inc> ...

  5. Oracle中常用的系统表

    1.dba开头的表 dba_users 数据库用户信息 dba_segments 表段信息 dba_extents 数据区信息 dba_objects 数据库对象信息 dba_tablespaces ...

  6. mybatis-插件开发

    在Executor.StatementHandler.parameterHandler.resultSetHandler创建的时候都有一步这样的操作xxxHandler=interceptorChai ...

  7. zabbix之二进制安装

    #:参考官方网站 https://www.zabbix.com/documentation/4.0/manual/installation/install_from_packages/debian_u ...

  8. spring-cloud-alibaba-dependencies版本问题

    org.springframework.cloud的spring-cloud-alibaba-dependencies管理的nacos最新版本是0.9.0.RELEASE,已经不再维护了,用起来有版本 ...

  9. SSM和springboot对比

    今天在开源中国上看到一篇讲SSM.SpringBoot讲的不错的回答,分享! https://www.oschina.net/question/930697_2273593 一.SSM优缺点应该分开来 ...

  10. 【科研】科研【合同】盖章流程/横向&#183;非涉密/电子科技大学

    [前置手续] 一.在科研管理系统里填单子,立项. 二.科研管理系统审核通过后,对于对面给好的合同,在合同系统里选择[合同业务发起-发起非标准合同],填单子. 三.会有一系列的审核,审核完成后打印合同备 ...