LeetCode 题解工作台

使每位学生都有座位的最少移动次数

一个房间里有 n 个 空闲 座位和 n 名 站着的 学生,房间用一个数轴表示。给你一个长度为 n 的数组 seats ,其中 seats[i] 是第 i 个座位的位置。同时给你一个长度为 n 的数组 students ,其中 students[j] 是第 j 位学生的位置。 你可以执行以下操作任意次…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

将两个数组分别排序,然后遍历两个数组,计算每个学生的座位与其实际座位的距离,将所有距离相加即为答案。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 为数组 `seats` 和 `students` 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

一个房间里有 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
lightbulb

解题思路

方法一:排序

将两个数组分别排序,然后遍历两个数组,计算每个学生的座位与其实际座位的距离,将所有距离相加即为答案。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 seatsstudents 的长度。

1
2
3
4
5
6
class Solution:
    def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
        seats.sort()
        students.sort()
        return sum(abs(a - b) for a, b in zip(seats, students))
speed

复杂度分析

指标
时间O(n + m)
空间O(m)
psychology

面试官常问的追问

外企场景
  • question_mark

    The interviewer expects recognition of greedy assignment as the core pattern.

  • question_mark

    They may hint at sorting both arrays to minimize distance without explicitly saying it.

  • question_mark

    Look for opportunities to validate that no two students share a seat after pairing.

warning

常见陷阱

外企场景
  • error

    Forgetting to sort both arrays leads to suboptimal total moves.

  • error

    Assigning students without checking one-to-one mapping can cause seat collisions.

  • error

    Counting moves incorrectly by using differences without absolute value produces wrong totals.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allowing multiple students per seat, requiring conflict resolution logic.

  • arrow_right_alt

    Seats and students may have different lengths, necessitating extra handling.

  • arrow_right_alt

    Introducing negative positions or larger ranges, requiring careful indexing or adjusted calculations.

help

常见问题

外企场景

使每位学生都有座位的最少移动次数题解:贪心·invariant | LeetCode #2037 简单