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.

 

Notes:

  • 1 <= ages.length <= 20000.
  • 1 <= ages[i] <= 120.

Rust Solution

struct Solution;
use std::collections::HashMap;

impl Solution {
    fn num_friend_requests(ages: Vec<i32>) -> i32 {
        let mut hm: HashMap<i32, i32> = HashMap::new();
        for age in ages {
            *hm.entry(age).or_default() += 1;
        }
        let mut res = 0;
        for (&a, v) in &hm {
            for (&b, u) in &hm {
                if !(b > a || 2 * b <= a + 14) {
                    res += v * u;
                    if a == b {
                        res -= v;
                    }
                }
            }
        }
        res
    }
}

#[test]
fn test() {
    let ages = vec![16, 16];
    let res = 2;
    assert_eq!(Solution::num_friend_requests(ages), res);
    let ages = vec![16, 17, 18];
    let res = 2;
    assert_eq!(Solution::num_friend_requests(ages), res);
    let ages = vec![20, 30, 100, 110, 120];
    let res = 3;
    assert_eq!(Solution::num_friend_requests(ages), res);
    let ages = vec![73, 106, 39, 6, 26, 15, 30, 100, 71, 35, 46, 112, 6, 60, 110];
    let res = 29;
    assert_eq!(Solution::num_friend_requests(ages), res);
}

Having problems with this solution? Click here to submit an issue on github.