[LinkedIn] Find Influencer from matrix of LinkedIn users

public interface InfluencerFinder {
    /** 
    * Given a matrix of following between N LinkedIn users (with ids from 0 to N-1): 
    * followingMatrix[i][j] == true iff user i is following user j 
    * thus followingMatrix[i][j] doesn't imply followingMatrix[j][i]. 
    * Let's also agree that followingMatrix[i][i] == false 
    * 
    * Influencer is a user who is: 
    * - followed by everyone else and 
    * - not following anyone himself 
    * 
    * This method should find an Influencer by a given matrix of following, 
    * or return -1 if there is no Influencer in this group. 
    */ 
    int getInfluencer(boolean[][] followingMatrix)
}

Solution from here:

//Logic: a person "i" is not an influencer if "i" is following any "j" or any "j" is not following "i"
//since there could be at most 1 influencer by the nature of the question
//we could maintain a candidate. Whenever we find a counter example, we update the candidate
int getInfluencer(vector<vector<bool> > M) {
    int cand=0;
    for(int i=1; i<M.size(); i++)
    {
        if(M[cand][i] == 1 || M[i][cand]==0)
        {
            cand = i;
        }
    }
    // now verify cand is indeed an influencer
    for(int j=0; j<M.size(); j++)
    {
        if(j==cand) continue;
        if(M[cand][j]==1 || M[j][cand]==0) return -1;
    }
    return cand;
}
//O(n^2) sol
int getInfluencer(vector<vector<bool> > M) {    
    for(int i=0; i<M.size(); i++) {
        bool is_influencer = true;
        for(int j=0; j<M.size(); j++) {
            if( i==j ) continue;            
            if( M[i][j] || !M[j][i] ) {
                is_influencer = false; 
                break; 
            }
        }
        if( is_influencer )
            return i;
    }
    return -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值