-
Notifications
You must be signed in to change notification settings - Fork 0
/
The Celebrity Problem CodingNinjas.cpp
80 lines (69 loc) · 1.5 KB
/
The Celebrity Problem CodingNinjas.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// stack, if anyone knows end decrease, f anyone des increase similar to two pinter
// tc=o(n+n)
// sc=o(n)
#include <bits/stdc++.h>
/*
This is signature of helper function 'knows'.
You should not implement it, or speculate about its implementation.
bool knows(int A, int B);
Function 'knows(A, B)' will returns "true" if the person having
id 'A' know the person having id 'B' in the party, "false" otherwise.
*/
int findCelebrity(int n) {
stack<int> stk;
for(int i=0;i<n;i++){
stk.push(i);
}
while(stk.size()>1){
int first=stk.top();
stk.pop();
int second=stk.top();
stk.pop();
if(knows(first,second)){
stk.push(second);
}else{
stk.push(first);
}
}
int top=stk.top();
for(int i=0;i<n;i++){
if(i!=top && (knows(top,i) || !knows(i,top)))
return -1;
}
return top;
}
// two pointer, if anyone knows end decrease, f anyone des increase
// tc=o(n+n)
// sc=o(1)
int findCelebrity(int n) {
int start=0,end=n-1;
while(start<=end){
if(knows(start,end)) start++;
else end--;
}
// cout<<end<<" "<<endl;;
for(int i=0;i<n;i++){
if(i!=start && (knows(start,i) || !knows(i,start))) return -1;
}
return start;
}
// calculate indegree and outddegree, whicher is id has ind n-1 and out 0 is celeb
// tc=(n*n)
// sc=(n)
int findCelebrity(int n) {
vector<int> ind(n,0);
vector<int> out(n,0);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(knows(i,j)){
ind[j]++;
out[i]++;
}
}
}
for(int i=0;i<n;i++){
if(ind[i]==n-1 && out[i]==0)
return i;
}
return -1;
}