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: 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
 1 class Solution {
 2     public int numFriendRequests(int[] ages) {
 3         int[] map = new int[121]; //每个年龄有多少人, 优化1 不用map用常数大小数组,这样时间和空间都是O(1)
 4         for (int age : ages) map[age]++;
 5         int count = 0;
 6         for (int i = 0; i <= 120; i++) {
 7             for (int j = 0; j <= 120; j++) {
 8                 if (valid(i, j)) {
 9                     count += map[i] * (i == j ? map[j] - 1 : map[j]); //注意i,j相等不能skip,因为可能多个相等年龄
10                 }
11             }
12         }
13         return count;
14     }
15     public boolean valid(int a, int b) {
16         return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100)); //其实条件2和3重复了
17     }
18 }

 

825. Friends Of Appropriate Ages

上一篇:文件夹管理: mv cp rm touch mkdir LS 创建文件夹 移动 删除 复制


下一篇:docker 简单部署 flask 多个app