当前位置:网站首页>Leetcdoe 2037. 使每位学生都有座位的最少移动次数(可以,一次过)
Leetcdoe 2037. 使每位学生都有座位的最少移动次数(可以,一次过)
2022-06-12 10:21:00 【我不是萧海哇~~~~】

一个房间里有 n 个座位和 n 名学生,房间用一个数轴表示。给你一个长度为 n 的数组 seats ,其中 seats[i] 是第 i 个座位的位置。同时给你一个长度为 n 的数组 students ,其中 students[j] 是第 j 位学生的位置。
你可以执行以下操作任意次:
- 增加或者减少第 i 位学生的位置,每次变化量为 1 (也就是将第 i 位学生从位置 x 移动到 x + 1 或者 x - 1)
请你返回使所有学生都有座位坐的 最少移动次数 ,并确保没有两位学生的座位相同。
请注意,初始时有可能有多个座位或者多位学生在 同一 位置。
示例 1:
输入:seats = [3,1,5], students = [2,7,4]
输出:4
解释:学生移动方式如下:
- 第一位学生从位置 2 移动到位置 1 ,移动 1 次。
- 第二位学生从位置 7 移动到位置 5 ,移动 2 次。
- 第三位学生从位置 4 移动到位置 3 ,移动 1 次。
总共 1 + 2 + 1 = 4 次移动。
示例 2:
输入:seats = [4,1,5,9], students = [1,3,2,6]
输出:7
解释:学生移动方式如下:
- 第一位学生不移动。
- 第二位学生从位置 3 移动到位置 4 ,移动 1 次。
- 第三位学生从位置 2 移动到位置 5 ,移动 3 次。
- 第四位学生从位置 6 移动到位置 9 ,移动 3 次。
总共 0 + 1 + 3 + 3 = 7 次移动。
示例 3:
输入:seats = [2,2,6,6], students = [1,3,2,6]
输出:4
解释:学生移动方式如下:
- 第一位学生从位置 1 移动到位置 2 ,移动 1 次。
- 第二位学生从位置 3 移动到位置 6 ,移动 3 次。
- 第三位学生不移动。
- 第四位学生不移动。
总共 1 + 3 + 0 + 0 = 4 次移动。
提示:
- n == seats.length == students.length
- 1 <= n <= 100
- 1 <= seats[i], students[j] <= 100
主要思路:先排序,然后求绝对值
Code:
class Solution {
public:
int minMovesToSeat(vector<int>& seats, vector<int>& students) {
int res=0;
sort(seats.begin(),seats.end());
sort(students.begin(),students.end());
for(int i=0;i<seats.size();i++)
{
res+=abs(students[i]-seats[i]);
}
return res;
}
};
边栏推荐
- 2021-02-22
- 4. creator mode
- np.meshgrid()函数 以及 三维空间中的坐标位置生成 以及 numpy.repeat()函数介绍
- 2021-09-13
- Introduction to encoding formats (ASCII, Unicode and UTF-8)
- PHP generate schedule
- Php:redis uses geospatial
- One test for twoorthree years, recording some thoughts on test exchange experience
- reflex
- [CEGUI] window environment compilation
猜你喜欢

Properties Chinese garbled code

Chapter 3 search

Quickly build oncyber io

Student management system

How high can C language reach by self-study alone?

JVM (VI) Virtual machine bytecode execution engine (with stack execution process and bytecode instruction table)

Love and hate in the Jianghu

2021-03-26
![[CEGUI] concept introduction](/img/a6/695d7f1a4e57c8438e2d1a4cad11dc.jpg)
[CEGUI] concept introduction

How to play the 2022 Taobao 618 Super Cat Games? Playing skills of 2022 Taobao 618 Cat Games
随机推荐
古董级MFC/GDI+框架LCD显示控件
[CEGUI] log system
2021-02-21
Cookie object
Antique mfc/gdi+ Frame LCD display control
容器江湖的爱恨情仇
MYSQL用户与权限管理,角色管理
Propagation of transactions
【实验】MySQL主从复制及读写分离
[DDS] dds-rpc implementation based on opendds
Implementation principle of redisson distributed lock
How to implement Web3.0 and digital fashion?
Win10 professional edition user name modification
MQTT 协议中文版
【926. 将字符串翻转到单调递增】
2021-02-12
[CEGUI] resource loading process
2021-02-22
Simple use of autojs
高通平台如何修改特殊电压