zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 85

    Find the Celebrity
    要点:

    • 这题从solution反过来想比较好:loop through n同时maintain一个candidate:如果cand认识某个i,那么modify cand。实际上检查另一个条件i不认识cand也可以,因为这2个条件是exclusive的
    • 这个过程保证了cand不认识其之后的所有人。两个问题:
      • 一是会不会漏掉之前可能的celebrity呢?不会,如果当前cand不know i,i不可能是candidate。
      • 因为只是确保了之后的所有人,会不会是False positive呢?所以要再loop确认结果。所以两个loop一个验证必要条件,一个验证充分条件

    https://repl.it/Cet1/1
    错误点:

    • 最后验证的时候要两个条件都验证,否则0 knows 1, 1 knows 0的情况会错
    # Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
    
    # Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
    
    # You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.
    
    # Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.
    
    # Hide Company Tags LinkedIn Facebook
    # Hide Tags Array
    
    # The knows API is already defined for you.
    # @param a, person a
    # @param b, person b
    # @return a boolean, whether a knows b
    # def knows(a, b):
    
    class Solution(object):
        def findCelebrity(self, n):
            """
            :type n: int
            :rtype: int
            """
            cand = 0
            for i in xrange(1,n):
            	if knows(cand, i):
            		cand = i
            
            for i in xrange(n):
            	if i!=cand:
            		if not knows(i,cand) or knows(cand, i):
            			return -1
            return cand                
    
  • 相关阅读:
    查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩 从SC表中选取score小于60的,并group by sid,having count 大于1
    SQL经典实例书上的数据代码
    mysql练习题
    mysql中alter语句
    如何解决SSH登录Solaris主机速度慢的问题
    Solaris10安装配置LDAP(iPlanet Directory Server )
    Oracle 11g oracle 用户密码过期问题 (ZT)
    Changing Controller Numbers in Solaris
    SPARC T4 RAID Setup (ZT)
    Oracle11g 配置DG broker
  • 原文地址:https://www.cnblogs.com/absolute/p/5815763.html
Copyright © 2011-2022 走看看