1. 程式人生 > >825. Friends Of Appropriate Ages

825. Friends Of Appropriate Ages

不可 題目 同齡人 prop notes i++ nds clas problem

問題描述:

Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.

Person A will NOT friend request person B (B != A) if any of the following conditions are true:

  • age[B] <= 0.5 * age[A] + 7
  • age[B] > age[A]
  • age[B] > 100 && age[A] < 100

Otherwise, A will friend request B.

Note that if A requests B, B does not necessarily request A. Also, people will not friend request themselves.

How many total friend requests are made?

Example 1:

Input: [16,16]
Output: 2
Explanation: 2 people friend request each other.

Example 2:

Input: [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.

Example 3:

Input: [20,30,100,110,120]
Output: 
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.

Notes:

  • 1 <= ages.length <= 20000.
  • 1 <= ages[i] <= 120.

解題思路:

一開始想到的是暴力破解法:即O(n2)的方法,但是顯然OJ是不會讓你過的:)

這裏參考了votrubac 的解法

只能說我沒有好好分析題意

遇見這種不等式沒能去化簡

由條件一: age[B] <= 0.5 * age[A] + 7

和條件二: age[B] > age[A]

可得 age[A] < 0.5 * age[A] + 7

即 age[A] < 14

當年齡小於14時,是不可以發出好友請求的。

由於題目限定: 1 <= ages[i] <= 120.

我們可以將每個年齡出現的個數存入一個固定大小的數組(這將花費我們O(n)的時間)

而由於遍歷固定大小的數組的時間是一定的,實際上是O(1)

根據我們上面得出的條件:

我們將從年齡為15的開始向後遍歷

對當前年齡,我們又可以分為兩種情況:

  1. 同齡人:cnt[i] * (cnt[i] - 1)

  2. 比TA小且滿足要求的人:由j = 0.5 * i + 8開始向後遍歷,且j < i

代碼:

class Solution {
public:
    int numFriendRequests(vector<int>& ages) {
        int cnt[121] = {};
        int ret = 0;
        for(int a : ages){
            cnt[a]++;
        }
        for(int i = 15; i < 121; i++){
            if(cnt[i] == 0) continue;
            ret += cnt[i] * (cnt[i]-1);
            for(int j = 0.5 * i + 8; j < i; j++)
                ret += cnt[j]*cnt[i];
        }
        return ret;
    }
};

825. Friends Of Appropriate Ages