使每位学生都有座位的最少移动次数【LC2037】
There are
nseats andnstudents in a room. You are given an arrayseatsof lengthn, whereseats[i]is the position of theithseat. You are also given the arraystudentsof lengthn, wherestudents[j]is the position of thejthstudent.You may perform the following move any number of times:
- Increase or decrease the position of the
ithstudent by1(i.e., moving theithstudent from positionxtox + 1orx - 1)Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.
Note that there may be multiple seats or students in the same position at the beginning.
元旦快乐啦
-
思路:要使总移动次数最少,那么要将每个学生移动至离其最近的座位,因此将座位和学生的位置进行升序排序,每个学生需要的移动次数即为对应位置相减,累加返回最终结果
-
实现
class Solution { public int minMovesToSeat(int[] seats, int[] students) { Arrays.sort(seats); Arrays.sort(students); int res = 0; for (int i = 0; i < seats.length; i++){ res += Math.abs(seats[i] - students[i]); } return res; } }- 复杂度
- 时间复杂度:O(n)O(n)O(n)
- 空间复杂度:O(1)O(1)O(1)
- 复杂度
-
实现
class Solution { public int minMovesToSeat(int[] seats, int[] students) { Arrays.sort(seats); Arrays.sort(students); int res = 0; for (int i = 0; i < seats.length; i++){ res += Math.abs(seats[i] - students[i]); } return res; } }- 复杂度
- 时间复杂度:O(n)O(n)O(n)
- 空间复杂度:O(1)O(1)O(1)
- 复杂度

该博客讨论了如何在给定座位和学生位置的情况下,通过最小化移动次数使每个学生都能坐在座位上。解决方案是首先对座位和学生的位置进行排序,然后计算每个学生到达最近座位所需的移动次数,并累加得到总移动次数。这是一个关于算法和数据结构的问题,主要涉及排序和数学优化。

被折叠的 条评论
为什么被折叠?



