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)
# Class definition for the solution
class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
# Initialize result and frequency array for ages
res = 0
ages_count = [0] * 121
# Count frequency of each age
for age in ages:
ages_count[age] += 1
# Create prefix sum array for cumulative age counts
pref_sum = [0] * 121
for i in range(1, 121):
pref_sum[i] = pref_sum[i - 1] + ages_count[i]
# Calculate friend requests for each age
for i in range(1, 121):
if ages_count[i] == 0: continue
val = int(0.5 * i) + 7
if i > val:
res += (pref_sum[i] - pref_sum[val] - 1) * ages_count[i]
return res