• LeetCode 277. Find the Celebrity


    原题链接在这里:https://leetcode.com/problems/find-the-celebrity/

    题目:

    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 - 1people 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.

    题解:

    先找一个candidate. 若是celebrity 认识 i, 说明i 有可能是celebrity. 就更新i为candidate.

    找到这个candidate 后 再扫一遍来判定这是不是一个合格的candidate, 若是出现candidate认识i 或者 i不认识candidate的情况, 说明这不是一个合格的candidate.

    Time Complexity: O(n). Space: O(1).

    AC Java:

     1 /* The knows API is defined in the parent class Relation.
     2       boolean knows(int a, int b); */
     3 
     4 public class Solution extends Relation {
     5     public int findCelebrity(int n) {
     6         if(n <= 1){
     7             return -1;
     8         }
     9         int celebrity = 0;
    10         //找一个candidate
    11         for(int i = 0; i<n; i++){
    12             if(knows(celebrity, i)){
    13                 celebrity = i;
    14             }
    15         }
    16         for(int i = 0; i<n; i++){
    17             //若是出现candidate认识i 或者 i不认识candidate的情况, 说明这不是一个合格的candidate
    18             if(i != celebrity && (knows(celebrity, i) || !knows(i, celebrity))){
    19                 return -1;
    20             }
    21         }
    22         return celebrity;
    23     }
    24 }

    类似Find the Town Judge.

  • 相关阅读:
    TCP和UDP的区别
    项目--华为商城---登录页面(一)
    Servlet(一)—— 文件上传(表单文件上传)
    LeetCode(一) —— 存在重复
    电脑右击不能创建txt文件
    边工作边刷题:70天一遍leetcode: day 92-2
    自底向上集成 Bottom-Up
    分层集成(线性关系) Layers
    基干集成(内核耦合度高) Backbone
    三明治集成(分而治之策略) 又分为传统型和改进型 Sandwich
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5343739.html
Copyright © 2020-2023  润新知