LeetCode 825 Friends Of Appropriate Ages

LeetCode 825 Friends Of Appropriate Ages

傳送門

題目分析

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.

給定一個數組作爲一羣人的年齡分佈,判斷這羣人中一共可以發送最多多少好友申請。

思考

首先題目中的B > A時A不會發送說明了一個人只能向年齡小於等於自己的人發送,由此可以先對數組進行排序,然後進行查找。

還有一個可以借鑑的就是同齡人發送的個數是一樣的,可以記錄在數組或者HashMap中,以便重用。

代碼實現

import java.util.Arrays;
import java.util.HashMap;

class Solution {
    // 判斷A是否會向B發送申請
    boolean good(int A, int B) {
        if (B <= 0.5 * A + 7) {
            return false;
        }
        if (B > 100 && A < 100) {
            return false;
        }

        return true;
    }

    public int numFriendRequests(int[] ages) {
        if (ages == null || ages.length <= 1) {
            return 0;
        }
        // 一個map記錄此年齡的人可以發送的請求個數
        HashMap<Integer, Integer> map = new HashMap<>();

        int ans = 0;
        // 進行排序,在內部循環的時候會用到
        Arrays.sort(ages);
        // 遍歷
        for (int i = 0; i < ages.length; i++) {
            // 重用以前數據
            if (map.containsKey(ages[i])) {
                ans += map.get(ages[i]);
                continue;
            }
            // 計算此年齡的人可以發送的請求數
            int sum = 0;
            for (int j = 0; j < ages.length && ages[j] <= ages[i]; j++) {
                if (i != j && good(ages[i], ages[j])) {
                    ++sum;
                }
            }
            map.put(ages[i], sum);
            ans += sum;
        }

        return ans;
    }
}

感想

HashMap可以用來重用已經計算了的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章