原文链接: https://leetcode-cn.com/problems/friends-of-appropriate-ages
英文原文
There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.
A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7age[y] > age[x]age[y] > 100 && age[x] < 100
Otherwise, x will send a friend request to y.
Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.
Return the total number of friend requests made.
Example 1:
Input: ages = [16,16] Output: 2 Explanation: 2 people friend request each other.
Example 2:
Input: ages = [16,17,18] Output: 2 Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Example 3:
Input: ages = [20,30,100,110,120] Output: 3 Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
Constraints:
n == ages.length1 <= n <= 2 * 1041 <= ages[i] <= 120
中文题目
人们会互相发送好友请求,现在给定一个包含有他们年龄的数组,ages[i] 表示第 i 个人的年龄。
当满足以下任一条件时,A 不能给 B(A、B不为同一人)发送好友请求:
age[B] <= 0.5 * age[A] + 7age[B] > age[A]age[B] > 100 && age[A] < 100
否则,A 可以给 B 发送好友请求。
注意如果 A 向 B 发出了请求,不等于 B 也一定会向 A 发出请求。而且,人们不会给自己发送好友请求。
求总共会发出多少份好友请求?
示例 1:
输入:[16,16] 输出:2 解释:二人可以互发好友申请。
示例 2:
输入:[16,17,18] 输出:2 解释:好友请求可产生于 17 -> 16, 18 -> 17.
示例 3:
输入:[20,30,100,110,120] 输出:3 解释:好友请求可产生于 110 -> 100, 120 -> 110, 120 -> 100.
提示:
1 <= ages.length <= 200001 <= ages[i] <= 120
通过代码
官方题解
方法 1:计数
想法
不考虑遍历所有的 20000 个人,我们只考虑遍历所有的元组 (age, count) 表示在这个年纪有多少人。因为最多只有 120 个可能的年纪,这会是一个很快的提升。
算法
对于每个元组 (ageA, countA),(ageB, countB),如果条件满足对应的年纪,那么久将 countA * countB 加入发好友请求的人数。
当 ageA == ageB 的时候我们就数多了:我们只有 countA * (countA - 1) 对好友请求,因为你不能和自己发送请求。
[]class Solution { public int numFriendRequests(int[] ages) { int[] count = new int[121]; for (int age: ages) count[age]++; int ans = 0; for (int ageA = 0; ageA <= 120; ageA++) { int countA = count[ageA]; for (int ageB = 0; ageB <= 120; ageB++) { int countB = count[ageB]; if (ageA * 0.5 + 7 >= ageB) continue; if (ageA < ageB) continue; if (ageA < 100 && 100 < ageB) continue; ans += countA * countB; if (ageA == ageB) ans -= countA; } } return ans; } }
[]class Solution(object): def numFriendRequests(self, ages): count = [0] * 121 for age in ages: count[age] += 1 ans = 0 for ageA, countA in enumerate(count): for ageB, countB in enumerate(count): if ageA * 0.5 + 7 >= ageB: continue if ageA < ageB: continue if ageA < 100 < ageB: continue ans += countA * countB if ageA == ageB: ans -= countA return ans
复杂度分析
- 时间复杂度:$O(A^2 + N)$,其中 $N$ 是人数,$A$ 是年龄的种树。
- 空间复杂度:$O(A)$,
count的空间开销。
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 7122 | 18039 | 39.5% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|