Leetcode P825 Java
执行用时:2 ms, 在所有 Java 提交中击败了82.92%的用户
内存消耗:45.3 MB, 在所有 Java 提交中击败了59.43%的用户
ideas
首先我们分析题得知年龄的范围在1-120区间,那么我们就设置一个长度为121的数组用来记录每个年龄共有多少人,
int n = ages.length;
int[] arr = new int[121];
int res =0 ;
for (int i = 0; i < n; i++) {
arr[ages[i]]++;
}
接下来我们遍历1-120区间的年龄的数据,查看有多少不再以下范围内
ages[y] <= 0.5 * ages[x] + 7
ages[y] > ages[x]
ages[y] > 100 && ages[x] < 100
如果ages[y] <= 0.5 * ages[x] + 7
就让y的年龄大一岁。其他都break,让x的年龄大一岁
if (y <= 0.5 * x + 7){
continue;
}
if (x < y){
break;
}
if (y > 100 && x < 100){
break;
}
如果年龄相同,就累加当前年龄有多少可以互发消息,如果不是就查看年龄为y的人数*年龄为x的人数。
if (x == y){
res += arr[x] * (arr[x]-1);
}else{
res += arr[x] * arr[y];
}
同时我们在做个优化,如果x的年龄为0,那么我们直接让x的年龄大一岁
if (arr[x] == 0){
continue;
}
Code
public int numFriendRequests(int[] ages) {
int n = ages.length;
int[] arr = new int[121];
int res =0 ;
for (int i = 0; i < n; i++) {
arr[ages[i]]++;
}
for (int x = 1; x <= 120 ; x++) {
if (arr[x] == 0){
continue;
}
for (int y = 1; y <= 120 ; y++) {
if (y <= 0.5 * x + 7){
continue;
}
if (x < y){
break;
}
if (y > 100 && x < 100){
break;
}
if (x == y){
res += arr[x] * (arr[x]-1);
}else{
res += arr[x] * arr[y];
}
}
}
return res;
}