LeetCode 825. 适龄的朋友

825. 适龄的朋友

解题思路:

解法一:

排序+双指针。先把ages从小到大排序,根据题目条件可知用户y要想被发送好友请求,其年龄应该满足:ages[y] > 0.5 * ages[x] + 7 && ages[y] <= ages[x]。我们可以通过设立双指针l来查找满足条件的左边界和r来查找满足条件的右边界。最后要累加和即可,注意累加的时候注意减去x本身。

class Solution {
public:
    int numFriendRequests(vector<int>& ages) {
      sort(ages.begin(), ages.end());
      int ans = 0, n = ages.size();
      for (int l = 0, r = 0, x = 0; x < n; ++ x) {
        if (ages[x] < 15) continue;
        while(r < n && ages[r] <= ages[x]) r++;
        while(l < x && ages[l] <= 0.5 * ages[x] + 7) l++;
        ans += (r - l - 1);
      }
      return ans;
    }
};

解法二:

计数排序+前缀和。我们可以统计每个年龄段出现的次数cnt,然后通过前缀和来统计每个区间(ages[x] * 0.5 + 7, ages[x]]的个数,同时注意乘上年龄出现的次数,累加每个年龄的和即可。

class Solution {
public:
    int numFriendRequests(vector<int>& ages) {
      vector<int> cnt(121, 0);
      for (const auto &age : ages) ++cnt[age];
      vector<int> pre(121, 0);
      for (int i = 1; i <= 120; ++ i)
        pre[i] = pre[i - 1] + cnt[i];
      int ans = 0;
      for (int age = 15; age <= 120; ++ age) {
        int bound = 0.5 * age + 7;
        ans += cnt[age] * (pre[age] - pre[bound] - 1);
      }
      return ans;
    }
};

posted on 2022-04-07 11:00  翔鸽  阅读(18)  评论(0编辑  收藏  举报