[LeetCode#277] Find the Celebrity

Problem:

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.

Analysis:

Even though the problem is not hard, the efficiency could vary a lot, and the concisness of the code could also vary a lot!!!
I have explored following mistakes and implementation until I reach the final solution.

Mistake 1:
Put return in "if-else". Note this is a very common mistake, you should always guanratee a default return at last.

        if (candidates.size() != 1) {
            return -1;
        } else{
            for (int i : candidates)
                return i;
        }

Line 27: error: missing return statement

Mistake 2:  Modify sets when iterate on it.
public class Solution extends Relation {
    public int findCelebrity(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("n is invalid");
        HashSet<Integer> candidates = new HashSet<Integer> ();
        for (int i = 0; i < n; i++)
            candidates.add(i);
        for (int i = 0; i < n; i++) {
            for (int j : candidates) {
                if (i != j) {
                    if (knows(i, j))
                        candidates.remove(i);
                    else
                        candidates.remove(j);
                }
            }
        }
        if (candidates.size() == 1) {
            for (int i : candidates)
                return i;
        }
        return -1;
    }
}

Runtime Error Message:
Line 26: java.util.ConcurrentModificationException

Note: this is absolutely allowed!!! A way to avoid this is to use a HashSet to record all the elements you want to remove. When you finish the iteration, then you can remove those elements through "set.removeAll()" method to remove them. 

public class Solution extends Relation {
    public int findCelebrity(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("n is invalid");
        HashSet<Integer> candidates = new HashSet<Integer> ();
        HashSet<Integer> excludes = new HashSet<Integer> ();
        for (int i = 0; i < n; i++)
            candidates.add(i);
        for (int i = 0; i < n; i++) {
            for (int j : candidates) {
                if (i != j) {
                    if (knows(i, j)) {
                        excludes.add(i);
                    } else{
                        excludes.add(j);
                    }
                }
            }
            candidates.removeAll(excludes);
        }
        if (candidates.size() == 1) {
            for (int i : candidates)
                return i;
        }
        return -1;
    }
}

Input:
0 knows 1; 1 knows 0.
Output:
1
Expected:
-1

As you can see from the error notification, the above solution could still be wrong. The problem is that even there maybe only "1 element" left in the candidates set, it may not be the answer.

case 1: iff such celebrity exist, there must one element left.
case 2: iff not exist, there also could be elements left in the Set, thus we have to do the final check to resure the left element is a celebrity/ 

Update:
public class Solution extends Relation {
    public int findCelebrity(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("n is invalid");
        HashSet<Integer> candidates = new HashSet<Integer> ();
        HashSet<Integer> excludes = new HashSet<Integer> ();
        for (int i = 0; i < n; i++)
            candidates.add(i);
        for (int i = 0; i < n; i++) {
            for (int j : candidates) {
                if (i != j) {
                    if (knows(i, j)) {
                        excludes.add(i);
                    } else{
                        excludes.add(j);
                    }
                }
            }
            candidates.removeAll(excludes);
        }
        for (int i : candidates) {
            for (int j = 0; j < n; j++) {
                if (i != j) {
                    if (knows(i, j) || !knows(j, i))
                        return -1;
                }
            }
        }
        for (int i : candidates)
            return i;
        return -1;
    }
}

We have used two HashSets in the above solution, and for each non-repeative comparision, we could eliminate one candidate out. Thus for the above code the time complexity is actually O(n).

Actually, using above conclusion, we could write the code into a more elegant way. We could use a stack to guarantee:
1. if there is a celebrity, it must remain in the stack(as long as there is an element)
2. there is no repeatitive comparision among candidate. 

We know for each comparision, we must be able to eliminate one element out.
1. iff A knows B, A must not the celebrity, since celebrity knows no one.
2. iff A did not know B, B must not the celebrity, since everyone knows celebrity.

while (stack.size() > 1) {
    int i = stack.pop();
    int j = stack.pop();
    if (knows(i, j))
        stack.push(j);
    else
        stack.push(i);
    }
}

Solution:

public class Solution extends Relation {
    public int findCelebrity(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("n is invalid");
        if (n == 1)
            return 0;
        Stack<Integer> stack = new Stack<Integer> ();
        for (int i  = 0; i < n; i++)
            stack.push(i);
        while (stack.size() > 1) {
            int i = stack.pop();
            int j = stack.pop();
            if (knows(i, j))
                stack.push(j);
            else
                stack.push(i);
        }
        int j = stack.pop();
        for (int i = 0; i < n; i++) {
            if (i != j) {
                if (!knows(i, j) || knows(j, i))
                    return -1;
            }
        }
        return j;
    }
}
时间: 2024-08-11 15:01:22

[LeetCode#277] Find the Celebrity的相关文章

LeetCode 277. 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 - 1 people know him/her but he/she does not know any of them. Now you want to find

277. Find the Celebrity - Medium

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

277. 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 - 1 people know him/her but he/she does not know any of them. Now you want to find

leetcode 锁掉的题目清单

也刷leetcode, 先把锁掉的题目留备份好了: 156 Binary Tree Upside Down  [1] Problem: Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tre

Leetcode 前 400 重点 250 题

这个重点题目是把Leetcode前400题进行精简,划分精简规则如下: 删除不常考,面试低频出现题目 删除重复代码题目(例:链表反转206题,代码在234题出现过) 删除过于简单题目(例:100题:Same Tree) 删除题意不同,代码基本相同题目(例:136 & 389,保留一个) 所有题目尽量保证客观公正,只是按大概率删除不常考题目,很多题目面经出现过, 但出现次数属于个位数或者只有一两家出现进行删除.所以如在面试中出现删除题目概不负责,这只是从概率上删除低频,简单题目. 旨在减轻大家的刷

LeetCode Problems List 题目汇总

No. Title Level Rate 1 Two Sum Medium 17.70% 2 Add Two Numbers Medium 21.10% 3 Longest Substring Without Repeating Characters Medium 20.60% 4 Median of Two Sorted Arrays Hard 17.40% 5 Longest Palindromic Substring Medium 20.70% 6 ZigZag Conversion Ea

Leetcode problems classified by company 题目按公司分类(Last updated: October 2, 2017)

Sorted by frequency of problems that appear in real interviews.Last updated: October 2, 2017Google (214)534 Design TinyURL388 Longest Absolute File Path683 K Empty Slots340 Longest Substring with At Most K Distinct Characters681 Next Closest Time482

过中等难度题目.0310

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.

继续过中等难度.0309

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.