LeetCode -- 825. 适龄的朋友
首推桶思想,计数排序算法。 桶的本质实际上是一种分类,将全集分为子集,装入各个桶内。
我们将桶的分类标准按照年龄来分,cnt[i]表示年龄为i的人数
年龄为i的人可以向 (i - 0.5 * i + 7]~ i)的人发送好友请求,所以res += cnt[i - 0.8 * i + 7] + ... + cnt[i] - 1(把自己给剪掉)
class Solution { public: int numFriendRequests(vector<int>& ages) { vector<int> cnt(121); for(auto age : ages) { cnt[age] ++ ; } vector<int> su(121); for(int i = 1; i <= 120; i ++ ) { su[i] = cnt[i] + su[i - 1]; } int res = 0; for(int i = 15; i <= 120; i ++ ) { if(cnt[i]) { int lim = i * 0.5 + 8; res += cnt[i] * (su[i] - su[lim] - 1); } } return res; } };
python class Solution: def numFriendRequests(self, ages: List[int]) -> int: cnt = [0] * 121 su = [0] * 121 for age in ages: cnt[age] += 1 for i in range(1, 121): su[i] = su[i - 1] + cnt[i] res = 0 for i in range(15, 121): if cnt[i] > 0: l = int(i * 0.5 + 8) res += cnt[i] * (su[i] - su[l - 1] - 1) return res
java class Solution { public int numFriendRequests(int[] ages) { int[] cnt = new int[121]; int[] su = new int[121]; for(int age : ages) { cnt[age] ++ ; } for(int i = 1; i <= 120; i ++ ) { su[i] = su[i - 1] + cnt[i]; } int res = 0; for(int i = 15; i <= 120; i ++ ) { int l = i / 2 + 8; res += cnt[i] * (su[i] - su[l - 1] - 1); } return res; } }
golang func numFriendRequests(ages []int) int { cnt := [121] int{} su := [121] int{} for _, val := range ages { cnt[val] ++ } for i := 1; i < 121; i ++ { su[i] = su[i - 1] + cnt[i] } res := 0 for i := 15; i < 121; i ++ { if cnt[i] > 0 { l := i / 2 + 8 res += cnt[i] * (su[i] - su[l - 1] - 1) } } return res }
js /** * @param {number[]} ages * @return {number} */ var numFriendRequests = function(ages) { let cnt = new Array(121).fill(0); let su = new Array(121).fill(0); for(let it of ages) { cnt[it] ++ ; } for(let i = 1; i < 121; i ++ ) { su[i] = su[i - 1] + cnt[i]; } let res = 0; for(let i = 15; i < 121; i ++ ) { if(cnt[i] > 0) { let l = Math.floor(i * 0.5 + 8); res += cnt[i] * (su[i] - su[l - 1] - 1); } } return res; };