给你一份 n 位朋友的亲近程度列表,其中 n 总是 偶数
对每位朋友 ipreferences[i] 包含一份 按亲近程度从高 到低排列 的朋友列表。换句话说,排在列表前面的朋友与 i 的亲近程度比排在列表后面的朋友更高。每个列表中的朋友均以 0n-1 之间的整数表示。
所有的朋友被分成几对,配对情况以列表 pairs 给出,其中 pairs[i] = [x<sub>i</sub>, y<sub>i</sub>] 表示 x<sub>i</sub>y<sub>i</sub> 配对,且 y<sub>i</sub>x<sub>i</sub> 配对。
但是,这样的配对情况可能会使其中部分朋友感到不开心。在 xy 配对且 uv 配对的情况下,如果同时满足下述两个条件, x 就会不开心:

  • xu 的亲近程度胜过 xy ,且
  • ux 的亲近程度胜过 uv
    返回 不开心的朋友的数目
    示例 1:
  1. 输入:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
  2. 输出:2
  3. 解释:
  4. 朋友 1 不开心,因为:
  5. - 1 0 配对,但 1 3 的亲近程度比 1 0 高,且
  6. - 3 1 的亲近程度比 3 2 高。
  7. 朋友 3 不开心,因为:
  8. - 3 2 配对,但 3 1 的亲近程度比 3 2 高,且
  9. - 1 3 的亲近程度比 1 0 高。
  10. 朋友 0 2 都是开心的。

示例 2:

输入:n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
输出:0
解释:朋友 0 和 1 都开心。

示例 3:

输入:n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
输出:4

提示:

  • 2 <= n <= 500
  • n 是偶数
  • preferences.length == n
  • preferences[i].length == n - 1
  • 0 <= preferences[i][j] <= n - 1
  • preferences[i] 不包含 i
  • preferences[i] 中的所有值都是独一无二的
  • pairs.length == n/2
  • pairs[i].length == 2
  • x<sub>i</sub> != y<sub>i</sub>
  • 0 <= x<sub>i</sub>, y<sub>i</sub> <= n - 1
  • 每位朋友都 恰好 被包含在一对中

解法一:哈希+模拟

func unhappyFriends(n int, preferences [][]int, pairs [][]int) int {
    res := 0
    // 二维数组,第一维是某个人,第二维是另一个人,值表示两个人之间的亲近排名在 第一维 里排名第几。
    order := make([][]int, n)
    for i, preference := range preferences {
        order[i] = make([]int, n)
        for j, p := range preference {
            order[i][p] = j
        }
    }

    // 匹配关系
    match := make([]int, n)
    for _, pair := range pairs {
        match[pair[0]] = pair[1]
        match[pair[1]] = pair[0]
    }

    for x, y := range match {
        idx := order[x][y]
        // 保证 x u 亲近程度高于 x y
        for _, u := range preferences[x][:idx] {
            v := match[u]
            // 保证 u x 亲近程度高于 u v
            if order[u][v] > order[u][x] {
                res++
                break
            }
        }
    }
    return res
}