LeetCode 题解工作台
适龄的朋友
在社交媒体网站上有 n 个用户。给你一个整数数组 ages ,其中 ages[i] 是第 i 个用户的年龄。 如果下述任意一个条件为真,那么用户 x 将不会向用户 y ( x != y )发送好友请求: ages[y] ages[y] > ages[x] ages[y] > 100 && ages[…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们可以用一个长度为 的数组 记录每个年龄的人数。 接下来,枚举所有可能的年龄对 $(\textit{ax}, \textit{ay})$,如果 和 不满足题目中的任意一个条件,这些年龄对 $(\textit{ax}, \textit{ay})$ 就可以互发好友请求。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
在社交媒体网站上有 n 个用户。给你一个整数数组 ages ,其中 ages[i] 是第 i 个用户的年龄。
如果下述任意一个条件为真,那么用户 x 将不会向用户 y(x != y)发送好友请求:
ages[y] <= 0.5 * ages[x] + 7ages[y] > ages[x]ages[y] > 100 && ages[x] < 100
否则,x 将会向 y 发送一条好友请求。
注意,如果 x 向 y 发送一条好友请求,y 不必也向 x 发送一条好友请求。另外,用户不会向自己发送好友请求。
返回在该社交媒体网站上产生的好友请求总数。
示例 1:
输入:ages = [16,16] 输出:2 解释:2 人互发好友请求。
示例 2:
输入:ages = [16,17,18] 输出:2 解释:产生的好友请求为 17 -> 16 ,18 -> 17 。
示例 3:
输入:ages = [20,30,100,110,120] 输出:3 解释:产生的好友请求为 110 -> 100 ,120 -> 110 ,120 -> 100 。
提示:
n == ages.length1 <= n <= 2 * 1041 <= ages[i] <= 120
解题思路
方法一:计数 + 枚举
我们可以用一个长度为 的数组 记录每个年龄的人数。
接下来,枚举所有可能的年龄对 ,如果 和 不满足题目中的任意一个条件,这些年龄对 就可以互发好友请求。
此时,如果 ,年龄相同,那么 和 之间的好友请求数为 ;否则,年龄不同,那么 和 之间的好友请求数为 。我们将这些好友请求数累加到答案中即可。
时间复杂度 ,其中 是数组 的长度,而 是年龄的最大值,本题中 。
class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
cnt = [0] * 121
for x in ages:
cnt[x] += 1
ans = 0
for ax, x in enumerate(cnt):
for ay, y in enumerate(cnt):
if not (ay <= 0.5 * ax + 7 or ay > ax or (ay > 100 and ax < 100)):
ans += x * (y - int(ax == ay))
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of binary search and two-pointer techniques.
- question_mark
Candidate suggests sorting as a first step for optimization.
- question_mark
Candidate efficiently calculates the number of valid requests without resorting to brute force.
常见陷阱
外企场景- error
Forgetting to handle edge cases, such as when people have very young or very old ages.
- error
Incorrectly calculating the valid age range for friend requests, especially when ages are close to boundaries.
- error
Attempting to brute force the solution without leveraging sorting and binary search for optimization.
进阶变体
外企场景- arrow_right_alt
Implement a solution without sorting the array, using only binary search to determine valid pairs.
- arrow_right_alt
Modify the problem to allow for weighted age differences when determining valid requests.
- arrow_right_alt
Adapt the problem for real-time computations with streaming data, requiring constant updates to the array of ages.