825. Friends Of Appropriate Ages
Last updated
Last updated
time: O(121*121), O(1)
space:O(121), O(1)
class Solution {
public int numFriendRequests(int[] ages) {
int count[] = new int[121];
for (int age : ages) {
count[age]++;
}
int res = 0;
for (int ageA = 0; ageA <= 120; ageA++) {
int countA = count[ageA];
for (int ageB = 0; ageB <= 120; ageB++) {
int countB = count[ageB];
if (notAbleToSendRequest(ageA, ageB)) {
continue;
}
countB = (ageA == ageB) ? countB-1 : countB; // 兩年齡相同時, should 扣掉自己的一個個數, (不能對自己發邀請)
res += countA*countB;
}
}
return res;
}
private boolean notAbleToSendRequest(int ageX, int ageY) {
return ageY <= 0.5*ageX+7 || ageY > ageX || (ageY > 100 && ageX < 100);
}
}
/*
16, 17, 17
1*2 = 2
1
16 17 18 => in no limitation: 6 why?
16 -> 17 18
17 -> 16,18
18 -> 16,17
so exclude yourself
(age, count)
countA * countB
ageA == ageB, countA * (countA - 1)
*/