适龄的朋友
难度:
标签:
题目描述
代码结果
运行时间: 40 ms, 内存: 16.8 MB
/*
* 思路:
* 使用Java Streams来简化迭代过程。我们可以利用流的特性来实现对每一对用户进行检查。
*/
import java.util.Arrays;
public class FriendRequestsStream {
public long numFriendRequests(int[] ages) {
return Arrays.stream(ages)
.boxed()
.flatMap(ageX -> Arrays.stream(ages)
.filter(ageY -> ageX != ageY && canSendRequest(ageX, ageY)))
.count();
}
private boolean canSendRequest(int ageX, int ageY) {
if (ageY <= 0.5 * ageX + 7) return false;
if (ageY > ageX) return false;
if (ageY > 100 && ageX < 100) return false;
return true;
}
}
解释
方法:
This solution utilizes a frequency array to count the occurrences of each age from 1 to 120. It creates a prefix sum array to quickly calculate the sum of frequencies up to any given age. The logic involves iterating over each age and determining the range of ages that can receive friend requests from that age based on the given conditions. For each valid age, the solution calculates the number of potential friend requests by multiplying the frequency of the current age by the number of users in the valid age range (using the prefix sum to find this number quickly). This method avoids the need for nested iterations over the `ages` array, thus improving efficiency.
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
如何确定边界条件`ages[y] <= 0.5 * ages[x] + 7`的最小有效年龄`y`?
▷🦆
为什么在计算可能的好友请求时,要使用`pref_sum[i] - pref_sum[val] - 1`来计算年龄`i`可以发送请求的用户数?
▷🦆
在计算前缀和数组`pref_sum`时,为什么`pref_sum[i]`的计算可以直接依赖`pref_sum[i-1]`而不需要额外的循环?
▷🦆
题解中提到的优化避免了嵌套迭代,这种方法具体是如何通过前缀和数组减少计算次数的?
▷