[抄题]:算法
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特别多的时候
[输入量]:空: 正常状况:特大:特小:程序里处理到的特殊状况:异常状况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼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)); } }