277. Find the Celebrity (k2)
作者:互联网
这道题是一道Graph题目,关于这种人际关系网,谁认识不认识谁的题目,用indegree,outdegree是没问题的,时间复杂度是O(n2):
/* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class Solution extends Relation { int[] indegree; int[] outdegree; public int findCelebrity(int n) { indegree = new int[n]; outdegree = new int[n]; for(int i = 0;i<n;i++){ for(int j=0;j<n;j++){ if(i!=j&&knows(i,j)){ indegree[j]++; outdegree[i]++; } } } for(int i=0;i<n;i++){ if(indegree[i]==n-1 && outdegree[i]==0) return i; } return -1; } }
因为这道题是要寻找一个特殊的人,也就是Celebrity,他/她不认识任何人,但是大家都认识他/她。那么对于这种名人,其实可以用two pass来筛选,时间复杂度O(n):
1. 找到大家都认识的candidate,或者不认识别人的candidate。
2. 进一步筛选,如果这candidate即不认识每个人,而每个人又都认识他/她,那答案就是他/她了。
3. 如果步骤2的candidate不符合条件,那么返回-1.
public int findCelebrity(int n) { int candi = 0; for(int i=0;i<n;i++){ if(!knows(i, candi)){ candi = i; } } /* for (int i = 0; i < n; i++) { if (knows(candi, i)) candi = i; } */ for (int i = 0; i < n; i++) { if (i == candi) continue; if (knows(candi, i) || !knows(i, candi)) return -1; } return candi; }
标签:candidate,认识,int,indegree,Celebrity,outdegree,public,k2,Find 来源: https://www.cnblogs.com/feiflytech/p/15841596.html