LeetCode 题解工作台
让所有学生保持开心的分组方法数
给你一个下标从 0 开始、长度为 n 的整数数组 nums ,其中 n 是班级中学生的总数。班主任希望能够在让所有学生保持开心的情况下选出一组学生: 如果能够满足下述两个条件之一,则认为第 i 位学生将会保持开心: 这位学生被选中,并且被选中的学生人数 严格大于 nums[i] 。 这位学生没有被选…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·排序
答案摘要
假设选出了 个学生,那么以下情况成立: - 如果 $nums[i] = k$,那么不存在分组方法;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个下标从 0 开始、长度为 n 的整数数组 nums ,其中 n 是班级中学生的总数。班主任希望能够在让所有学生保持开心的情况下选出一组学生:
如果能够满足下述两个条件之一,则认为第 i 位学生将会保持开心:
- 这位学生被选中,并且被选中的学生人数 严格大于
nums[i]。 - 这位学生没有被选中,并且被选中的学生人数 严格小于
nums[i]。
返回能够满足让所有学生保持开心的分组方法的数目。
示例 1:
输入:nums = [1,1] 输出:2 解释: 有两种可行的方法: 班主任没有选中学生。 班主任选中所有学生形成一组。 如果班主任仅选中一个学生来完成分组,那么两个学生都无法保持开心。因此,仅存在两种可行的方法。
示例 2:
输入:nums = [6,0,3,3,6,7,2,7] 输出:3 解释: 存在三种可行的方法: 班主任选中下标为 1 的学生形成一组。 班主任选中下标为 1、2、3、6 的学生形成一组。 班主任选中所有学生形成一组。
提示:
1 <= nums.length <= 1050 <= nums[i] < nums.length
解题思路
方法一:排序 + 枚举
假设选出了 个学生,那么以下情况成立:
- 如果 ,那么不存在分组方法;
- 如果 ,那么学生 不被选中;
- 如果 ,那么学生 被选中。
因此,被选中的学生一定是排序后的 数组中的前 个元素。
我们在 范围内枚举 ,对于当前选出的学生人数 ,我们可以得到组内最大的学生编号 ,数字为 。如果 并且 ,那么不存在分组方法;如果 并且 ,那么不存在分组方法。否则,存在分组方法,答案加一。
枚举结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 为数组长度。
class Solution:
def countWays(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
ans = 0
for i in range(n + 1):
if i and nums[i - 1] >= i:
continue
if i < n and nums[i] <= i:
continue
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for an understanding of how sorting and grouping can simplify the problem.
- question_mark
Check if the candidate is able to identify the key observation about grouping students with the same happiness value.
- question_mark
Assess whether the candidate can correctly evaluate the number of ways to form valid student groups.
常见陷阱
外企场景- error
Failing to correctly group students by their happiness value and considering invalid groupings.
- error
Overcomplicating the problem by missing the key observation that students with the same value must either be included together or excluded.
- error
Misunderstanding the time complexity and assuming the problem can be solved in linear time without sorting.
进阶变体
外企场景- arrow_right_alt
Change the problem to allow partial selections of students, introducing more complexity in the valid groupings.
- arrow_right_alt
Alter the input such that students have a wider range of happiness values, which increases the number of possible groupings.
- arrow_right_alt
Introduce constraints that limit the size of groups, requiring a more efficient solution to handle large inputs.