classSolution { public: intnumFriendRequests(vector<int>& ages){ int n = ages.size(); sort(ages.begin(), ages.end()); int left = 0, right = 0, ans = 0; for (int age: ages) { if (age < 15) { continue; } while (ages[left] <= 0.5 * age + 7) { ++left; } while (right + 1 < n && ages[right + 1] <= age) { ++right; } ans += right - left; } return ans; } };
publicclassSolution { publicintNumFriendRequests(int[] ages) { int n = ages.Length; Array.Sort(ages); int left = 0, right = 0, ans = 0; foreach (int age in ages) { if (age < 15) { continue; } while (ages[left] <= 0.5 * age + 7) { ++left; } while (right + 1 < n && ages[right + 1] <= age) { ++right; } ans += right - left; } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defnumFriendRequests(self, ages: List[int]) -> int: n = len(ages) ages.sort() left = right = ans = 0 for age in ages: if age < 15: continue while ages[left] <= 0.5 * age + 7: left += 1 while right + 1 < n and ages[right + 1] <= age: right += 1 ans += right - left return ans
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcnumFriendRequests(ages []int) (ans int) { sort.Ints(ages) left, right := 0, 0 for _, age := range ages { if age < 15 { continue } for ages[left]*2 <= age+14 { left++ } for right+1 < len(ages) && ages[right+1] <= age { right++ } ans += right - left } return }
intnumFriendRequests(int* ages, int agesSize){ qsort(ages, agesSize, sizeof(int), cmp); int left = 0, right = 0, ans = 0; for (int i = 0; i < agesSize; ++i) { if (ages[i] < 15) { continue; } while (ages[left] <= 0.5 * ages[i] + 7) { ++left; } while (right + 1 < agesSize && ages[right + 1] <= ages[i]) { ++right; } ans += right - left; } return ans; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var numFriendRequests = function(ages) { const n = ages.length; ages.sort((a, b) => a - b); let left = 0, right = 0, ans = 0; for (const age of ages) { if (age < 15) { continue; } while (ages[left] <= 0.5 * age + 7) { ++left; } while (right + 1 < n && ages[right + 1] <= age) { ++right; } ans += right - left; } return ans; };