825. Friends Of Appropriate Ages
Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.
Person A will NOT friend request person B (B != A) if any of the following conditions are true:
age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
Otherwise, A will friend request B.
Note that if A requests B, B does not necessarily request A. Also, people will not friend request themselves.
How many total friend requests are made?
Example 1:
Input: [16,16]
Output: 2
Explanation: 2 people friend request each other.
Example 2:
Input: [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Example 3:
Input: [20,30,100,110,120]
Output:
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
Notes:
1 <= ages.length <= 20000.
1 <= ages[i] <= 120.
方法1: sort, TLE
思路:
age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
首先将所有人的年龄都sort一遍,为了满足条件2,从后向前遍历,只统计在当前点左边的数字。当前点可以向左边的每一个人发出申请,直到条件1不再满足。另外,需要处理特殊情况,a 和 b的年龄一样,a也会向b发出申请。
易错点
- age[B] >= 15: 为了使[0.5 * B + 7, B]成为一个合理的区间,必须使0.5 * B + 7 < B成立。
Complexity
Time complexity: O(n log n)
Spage complexity: O(1)
class Solution {
public:
int numFriendRequests(vector<int>& ages) {
int result = 0;
sort(ages.begin(), ages.end());
for (int i = ages.size() - 1; i >= 1; i--) {
for (int j = i - 1; j >= 0 && ages[j] >= 0; j--) {
if (ages[j] > 0.5 * ages[i] + 7) result ++;
if (ages[j] == ages[i]) result++;
}
}
return result;
}
};
方法2: count sort
思路:
第一次遍历记录每个年龄有多少人,第二次遍历统计presum。按之前的想法从后向前遍历第三遍,对于每个年龄上的人,可以直接计算出年龄下限,求出区间内一共有多少人,记录为people。在当前年龄上的人可以和所有这些人request,除了自己。所以累加(people - 1) * count[i]次request。
Complexity
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int numFriendRequests(vector<int>& ages) {
int result = 0;
vector<int> count(121, 0), presum(121, 0);
for (int a: ages) count[a]++;
for (int i = 1; i <= 120; i++) {
presum[i] = presum[i - 1] + count[i];
}
for (int i = 120; i >= 15; i--) {
int people = presum[i] - presum[i * 0.5 + 7];
result += (people - 1) * count[i];
}
return result;
}
};