Influencer Finder

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)

 

和Find the celebrity 非常类似

int getInfluencer(vector<vector<bool> > M) {
    int candidate = 0;
    for(int i=1; i<M.size(); i++)
    {
        if(M[candidate][i] == true || M[i][candidate]==false)
        {
            candidate = i;
        }
    }
    // now verify candidate is indeed an influencer
    for(int j=0; j<M.size(); j++)
    {
        if(j==candidate) continue;
        if(M[candidate][j]==true || M[j][candidate]==false) return -1;
    }
    return candidate;
}

 

posted @ 2016-01-24 01:27  Hygeia  阅读(328)  评论(0编辑  收藏  举报