LeetCode 5512. 统计不开心的朋友 模拟 哈希

地址 https://leetcode-cn.com/problems/count-unhappy-friends/

算法1
这一题感觉很迷,考点是模拟和哈希?
将给于的数据转换成哈希便于查找(使用数组下标会更加快速定位,我这里使用的是map)
然后根据题意模拟,进行处理.

C++ 代码

class Solution {
public:
 map<int, int> g[600];
bool Check(int x, int y, int u, int v) {
    if (g[x][u] <  g[x][y] && g[u][x] < g[u][v]) 
        return true;
    return false;
}
int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {
    if (pairs.size() <= 1) return 0;
    for (int i = 0; i < preferences.size(); i++) {
        for (int j = 0; j < preferences[i].size(); j++) {
            g[i][preferences[i][j]] = j;
        }
    }
    set<int> ss;
    for (int i = 0; i < pairs.size(); i++) {
        for (int j = i + 1; j < pairs.size(); j++) {
            int x = pairs[i][0]; int y = pairs[i][1];
            int u = pairs[j][0]; int v = pairs[j][1];

            if (Check(x, y, u, v) || Check(x, y, v, u)) ss.insert(x);
            if (Check(y, x, u, v) || Check(y, x, v, u)) ss.insert(y);

            if (Check(u,v,x,y) || Check(u,v,y,x)) ss.insert(u);
            if (Check(v,u,x,y) || Check(v,u,y,x)) ss.insert(v);
        }
    }
    return ss.size();
}
};

作者:itdef
链接:https://www.acwing.com/solution/content/20677/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

使用数组下标进行数据 定位

class Solution {
public:
    int g[600][600];
    int ans[600];
    
    bool Check(int x,int y ,int u,int v){
        if (g[x][u] <  g[x][y] && g[u][x] < g[u][v]) 
            return true;
        return false;
    }
    
    int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {
        memset(g,0,sizeof g);
        memset(ans,0,sizeof ans);
        
        for(int i = 0; i< preferences.size();i++){
            for(int j = 0;j < preferences[i].size();j++){
                int frindId = preferences[i][j];
                g[i][frindId] = j;
            }
        }
        
        for (int i = 0; i < pairs.size(); i++) {
            for (int j = i + 1; j < pairs.size(); j++) {
                int x = pairs[i][0]; int y = pairs[i][1];
                int u = pairs[j][0]; int v = pairs[j][1];   
                
                if (Check(x, y, u, v) || Check(x, y, v, u)) ans[x] =1;
                if (Check(y, x, u, v) || Check(y, x, v, u)) ans[y] =1 ;

                if (Check(u,v,x,y) || Check(u,v,y,x)) ans[u] = 1;
                if (Check(v,u,x,y) || Check(v,u,y,x)) ans[v] =1;
                
            }
        }
        
        int ret =0;
        for(int i=0;i < 600;i++){
            if(ans[i] == 1) ret++;
        }
        
        return ret;
    }
};

作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/13664104.html