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.ide

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

How many total friend requests are made?優化

 [暴力解法]:spa

時間分析:debug

空間分析:code

 [優化後]:blog

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思惟問題]:

用sliding window寫不出

至少能夠返回來用暴力作法啊

[一句話思路]:

duplicate的數組徹底能夠用hashmap來存數,特別是duplicate特別多的時候

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. 一開始沒有先想好,hashmap存錯了。先想好再寫

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

index 仍是 nums[index]下次能夠檢查下

[總結]:

有duplicate的數組徹底能夠用hashmap來存數

[複雜度]:Time complexity: O(n^2) Space complexity: O(n)

[英文數據結構或算法,爲何不用別的數據結構或算法]:

有duplicate的數組徹底能夠用hashmap來存數,特別是duplicate特別多的時候

[算法思想:遞歸/分治/貪心]:

[關鍵模板化代碼]:

兩個變量的雙重循環:

for (int a : map.keySet()) for (int b : map.keySet())

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

class Solution {
    public int numFriendRequests(int[] ages) {
        //cc
        if (ages == null || ages.length == 0) return 0;
        
        //ini: hashmap: age,count
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < ages.length; i++) map.put(ages[i], map.getOrDefault(ages[i], 0) + 1);
        int res = 0;
        
        //for loop: return a* b or a * (a - 1)
        for (int a : map.keySet()) for (int b : map.keySet()) {
            if (valid(a, b)) 
                res += map.get(a) * (map.get(b) - (a == b ? 1 : 0));
        }
        return res;
    }
    
    public boolean valid(int a, int b) {
        return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100));
    }
}
View Code
相關文章
相關標籤/搜索