LeetCode 825. Friends Of Appropriate Ages
阿新 • • 發佈:2018-11-07
題解
看似簡單,其實也簡單,就是出題人故意挖了坑等你跳。
第一坑,冗餘條件3,和2一個意思。
第二坑,排序無能,爆時間。
躲了這倆坑就基本明白了,就是桶排序。
ps: 我的程式碼還可以優化,可以再縮減遍歷的空間。
Code
int cot[121];
int numFriendRequests(vector<int>& ages) {
int n = ages.size();
for(int i=0;i<=120;i++) cot[i]=0;
int big=-1;
for(int age:ages){
cot[age]++;
big=max(age,big);
}
int res=0;
for(int i=0;i<=big;i++){
if(cot[i]!=0){
for(int j=0;j<i;j++){
if(cot[j]==0) continue;
else if(j>(i/2+7)) res+=cot[j]* cot[i];
}
if(i>14) res+= cot[i]*(cot[i]-1);
}
}
return res;
}