列表

详情


1583. 统计不开心的朋友

给你一份 n 位朋友的亲近程度列表,其中 n 总是 偶数

对每位朋友 ipreferences[i] 包含一份 按亲近程度从高到低排列 的朋友列表。换句话说,排在列表前面的朋友与 i 的亲近程度比排在列表后面的朋友更高。每个列表中的朋友均以 0n-1 之间的整数表示。

所有的朋友被分成几对,配对情况以列表 pairs 给出,其中 pairs[i] = [xi, yi] 表示 xiyi 配对,且 yixi 配对。

但是,这样的配对情况可能会使其中部分朋友感到不开心。在 xy 配对且 uv 配对的情况下,如果同时满足下述两个条件,x 就会不开心:

返回 不开心的朋友的数目

 

示例 1:

输入:n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
输出:2
解释:
朋友 1 不开心,因为:
- 1 与 0 配对,但 1 与 3 的亲近程度比 1 与 0 高,且
- 3 与 1 的亲近程度比 3 与 2 高。
朋友 3 不开心,因为:
- 3 与 2 配对,但 3 与 1 的亲近程度比 3 与 2 高,且
- 1 与 3 的亲近程度比 1 与 0 高。
朋友 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

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) { } };

golang 解法, 执行用时: 48 ms, 内存消耗: 9.2 MB, 提交时间: 2022-11-26 16:56:56

func unhappyFriends(n int, preferences [][]int, pairs [][]int) (ans int) {
    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 _, p := range pairs {
        match[p[0]] = p[1]
        match[p[1]] = p[0]
    }

    for x, y := range match {
        index := order[x][y]
        for _, u := range preferences[x][:index] {
            v := match[u]
            if order[u][x] < order[u][v] {
                ans++
                break
            }
        }
    }
    return
}

python3 解法, 执行用时: 60 ms, 内存消耗: 26.2 MB, 提交时间: 2022-11-26 16:56:35

class Solution:
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        order = [[0] * n for _ in range(n)]
        for i in range(n):
            for j in range(n - 1):
                order[i][preferences[i][j]] = j
        
        match = [0] * n
        for x, y in pairs:
            match[x] = y
            match[y] = x

        unhappyCount = 0
        for x in range(n):
            y = match[x]
            index = order[x][y]
            for i in range(index):
                u = preferences[x][i]
                v = match[u]
                if order[u][x] < order[u][v]:
                    unhappyCount += 1
                    break
        
        return unhappyCount

上一题