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可以用來重用已經計算了的數據。
總結
以上是生活随笔為你收集整理的LeetCode 825 Friends Of Appropriate Ages的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: vmtools的安装和使用
- 下一篇: 推荐一款非常实用的VR手势插件VRBas
