LeetCode 1583. 统计不开心的朋友

题目

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

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

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

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

x 与 u 的亲近程度胜过 x 与 y,且
u 与 x 的亲近程度胜过 u 与 v
返回 不开心的朋友的数目 。

示例 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

提示:

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
xi != yi
0 <= xi, yi <= n - 1
每位朋友都 恰好 被包含在一对中

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-unhappy-friends
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

构建一个辅助的亲近矩阵

class Solution {
    public int [][] score;
    public boolean chk(int[][] preferences,int x,int y,int u,int v){
        return score[x][u]>score[x][y]&&score[u][x]>score[u][v];
    }
    public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
        int ans=0;
        int[][] score=new int[n][n];
        for(int i=0;i<n;i++){
            for(int j=0;j<preferences[i].length;j++){
                score[i][preferences[i][j]] = n-1-j;
            }
        }
        this.score=score;
        int[] flag=new int[n];
        for(int i=0;i<n/2;i++){
            for(int j=i+1;j<n/2;j++){
                int a=pairs[i][0],b=pairs[i][1],c=pairs[j][0],d=pairs[j][1];
                if(flag[a]==0&&(chk(preferences,a,b,c,d)||chk(preferences,a,b,d,c))) flag[a]=1;
                if(flag[b]==0&&(chk(preferences,b,a,c,d)||chk(preferences,b,a,d,c))) flag[b]=1;
                if(flag[c]==0&&(chk(preferences,c,d,a,b)||chk(preferences,c,d,b,a))) flag[c]=1;
                if(flag[d]==0&&(chk(preferences,d,c,a,b)||chk(preferences,d,c,b,a))) flag[d]=1;
            }
        }
        for(int i=0;i<n;i++){
            if(flag[i]==1) ans++;
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wydxry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值