825. Friends Of Appropriate Ages**
825. Friends Of Appropriate Ages**
https://leetcode.com/problems/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: Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.Notes:
- 1 <= ages.length <= 20000.
- 1 <= ages[i] <= 120.
前言
有個(gè)笑話, 我必須笑一下:
因?yàn)槲以趯懘a的過程中也發(fā)現(xiàn)了這個(gè)問題, 然后停下來開始懷疑了人生 … 🤣🤣🤣
C++ 實(shí)現(xiàn) 1
我的思路稍微復(fù)雜一些, 要簡潔的方法可以看 C++ 實(shí)現(xiàn) 2.
從第二個(gè)條件可以發(fā)現(xiàn), 年輕的不會和年老的交友, 因此對年齡從小到大排序, 從后向前開始考慮. 對于 ages[i], 它只能和 [0 ... i - 1] 范圍內(nèi)的人交友. 但這里有個(gè)例外, 即 ages[i] == ages[i - 1] 時(shí), 此時(shí) ages[i - 1] 也能和 ages[i] 交友, 這種特殊情形我們之后考慮.
由于 ages[i] 不會和 age[B] <= 0.5 * age[i] + 7 的人交朋友, 其實(shí)就是在數(shù)組找 0.5 * age[i] + 7 的 upper_bound, 即第一個(gè)大于 0.5 * age[i] + 7 的數(shù) (更具體是 int(std::floor(ages[i] / 2.)) + 7, 代入一個(gè)具體的數(shù)值進(jìn)去就會發(fā)現(xiàn)是 floor 而不是 ceil.). 第三個(gè)條件 age[B] > 100 && age[A] < 100 是冗余的, 包含于條件二, 因此不用考慮. 那么 ages[i] 能交友的范圍為 [j, i - 1], 個(gè)數(shù)就是 (i - 1) + 1 - j = i - j 個(gè). 然而這里有兩個(gè)問題:
- 如果 j 不存在, 即 upper_bound 不存在, 那么 j = ages.size(), i - j 此時(shí)小于 0, 因此最后用 std::max(i - j, 0) 表示 ages[i] 能交友的個(gè)數(shù).
- 另外還需要考慮 ages[i] == ages[i + 1] 的情況, 此時(shí) ages[i] 的交友個(gè)數(shù)其實(shí)和 ages[i + 1] 的交友個(gè)數(shù)一樣, 因此用 prev 表示 ages[i + 1] 的交友個(gè)數(shù); 當(dāng)訪問到 ages[i] 時(shí), 如果 ages[i] == ages[i+ 1], 那么交友個(gè)數(shù)就是 prev.
C++ 實(shí)現(xiàn) 2
來自 LeetCode Submission. 由于年齡的大小是有限制的, 在 0 ~ 120 之間, 因此可以用數(shù)組保存各個(gè)年齡的人數(shù), 然后過濾不滿足條件的交友關(guān)系, 另外注意不能和自己交友.
class Solution { public:int numFriendRequests(vector<int>& ages) {vector<int> count(121, 0);int ret = 0;for (int age : ages) count[age]++;for (int i = 0; i < 121; i++) {for (int j = 0; j < 121; j++) {if (j <= 0.5 * i + 7) continue;if (j > i) continue;if (j > 100 && i < 100) continue;ret += count[i] * count[j];if (i == j) ret -= count[i]; // 不能和自己交友} }return ret;} };總結(jié)
以上是生活随笔為你收集整理的825. Friends Of Appropriate Ages**的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hcne学习笔记
- 下一篇: 百度html编辑器 xss,百度uedi