※ 引述《SecondRun (南爹抠打)》之铭言:
: 2037. Minimum Number of Moves to Seat Everyone
: 有 n 个座位和 n 个学生在一个房间里。给你一个长度为 n 的 seats 阵列,其中 seats[i] 是第 i 个座位的位置。同样地,给你一个长度为 n 的 students 阵列,其中 students[j] 是第 j 个学生的位置。
: 你可以进行以下任意次数的移动:
: 增加或减少第 i 个学生的位置 1 (即,将第 i 个学生从位置 x 移动到 x + 1 或 x - 1)
: 返回将每个学生移动到一个座位的最小移动次数,使得没有两个学生在同一个座位上。
: 请注意,一开始可能有多个座位或学生位于相同位置。
: Example 1:
: Input: seats = [3,1,5], students = [2,7,4]
: Output: 4
: Explanation: The students are moved as follows:
: - The first student is moved from from position 2 to position 1 using 1 move.
: - The second student is moved from from position 7 to position 5 using 2 moves.
: - The third student is moved from from position 4 to position 3 using 1 move.
: In total, 1 + 2 + 1 = 4 moves were used.
: 思考: 贪婪
: C# code:
: public class Solution {
: public int MinMovesToSeat(int[] seats, int[] students) {
: Array.Sort(seats);
: Array.Sort(students);
: int result = 0;
: int len = seats.Length;
: for (int i=0; i<len; i++)
: {
: result += Math.Abs(seats[i] - students[i]);
: }
: return result;
: }
: }
思路:
差不多
Python Code:
class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
seats.sort()
students.sort()
result = 0
for i in range(len(seats)):
result += abs(seats[i] - students[i])
return result