使每位学生都有座位的最少移动次数【LC2037】
There are
n
seats andn
students in a room. You are given an arrayseats
of lengthn
, whereseats[i]
is the position of theith
seat. You are also given the arraystudents
of lengthn
, wherestudents[j]
is the position of thejth
student.You may perform the following move any number of times:
- Increase or decrease the position of the
ith
student by1
(i.e., moving theith
student from positionx
tox + 1
orx - 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)
- 复杂度