|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +/* brute time:O(n^2) space:O(1) |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + // Function to find if there is a celebrity in the party or not. |
| 8 | + int celebrity(vector<vector<int>>& mat) { |
| 9 | + int n = mat.size(); |
| 10 | + vector<int> knowMe(n, 0); |
| 11 | + vector<int> Iknow(n, 0); |
| 12 | + |
| 13 | + // Iterate over the matrix to populate knowMe and Iknow arrays |
| 14 | + for (int i = 0; i < n; i++) { |
| 15 | + for (int j = 0; j < n; j++) { |
| 16 | + if (mat[i][j] == 1) { |
| 17 | + knowMe[j]++; |
| 18 | + Iknow[i]++; |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // Check for a celebrity |
| 24 | + for (int i = 0; i < n; i++) { |
| 25 | + if (knowMe[i] == n - 1 && Iknow[i] == 0) { |
| 26 | + return i; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return -1; // No celebrity found |
| 31 | + } |
| 32 | +}; |
| 33 | +*/ |
| 34 | + |
| 35 | +// time:O(2n) space:O(1) |
| 36 | +class Solution { |
| 37 | +public: |
| 38 | + |
| 39 | + int celebrity(vector<vector<int>>& mat) { |
| 40 | + int n = mat.size(); |
| 41 | + int top = 0, bottom = n - 1; |
| 42 | + |
| 43 | + // Narrow down the candidate |
| 44 | + while (top < bottom) { |
| 45 | + if (mat[top][bottom] == 1) { |
| 46 | + top++; |
| 47 | + } else { |
| 48 | + bottom--; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Verify the candidate |
| 53 | + for (int i = 0; i < n; i++) { |
| 54 | + if (i != top) { // Skip checking the diagonal |
| 55 | + if (mat[top][i] == 1 || mat[i][top] == 0) { |
| 56 | + return -1; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return top; // The candidate is a celebrity |
| 62 | + } |
| 63 | +}; |
| 64 | + |
| 65 | + |
| 66 | +int main() { |
| 67 | + Solution sol; |
| 68 | + |
| 69 | + // Example input matrix |
| 70 | + vector<vector<int>> mat = { |
| 71 | + {0, 1, 0}, |
| 72 | + {0, 0, 0}, |
| 73 | + {0, 1, 0} |
| 74 | + }; |
| 75 | + |
| 76 | + int result = sol.celebrity(mat); |
| 77 | + |
| 78 | + if (result != -1) { |
| 79 | + cout << "Celebrity ID: " << result << endl; |
| 80 | + } else { |
| 81 | + cout << "No Celebrity Found" << endl; |
| 82 | + } |
| 83 | + |
| 84 | + return 0; |
| 85 | +} |
0 commit comments