Leetcode 277 Find the Celebrity

Problem:

在这里插入图片描述

Analysis:

method1:
first of all, we can use the array with 2 dimensions to check each pair, which time complexity will be O(n^2)

method2:

  1. the first pass for all the people, find the celebrity candidate who doesn’t know anyone.
  • if (knows(A, B)):
    * A is not Celebrity;
  • else:
    * B is not Celebrity }
  1. the second pass, to make sure that the candidate is indeed the celebrity, or return -1;
/**
 * 
 * @author shaohua
 *boolean knows(A, B)
 *
 * 1. find the celebrity candidate who doesn't know the person behind him
 * 2. make sure candidate is celebrity
 *
 */

public class Solution1 {
	public int findCelebrity(int n) {
		
		int candidate = 0;
		for (int i=1; i<n; i++) {
			if (knows(candidate, i)) {
				candidate = i;
			}
		}
		
		for(int i=0; i<n; i++) {
			if (candidate == i) {
				continue;
			}
			
			if (knows(candidate,i) || !knows(i,candidate)) {
				return -1;
			}
		}
		
		return candidate;	
	}	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值