Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Lesson learnt: Get rid of XX algorithm routines clogging your mind and focus\enjoy the problem itself!

// Forward declaration of the knows API.
bool knows(int a, int b);

class Solution {
public:
    int findCelebrity(int n) 
    {
        //  Pass 1: pick out a potential candidate
        int cand = -1;
        for(int i = 0 ; i < n ; i ++)
        {
            if(cand == -1 || !knows(i, cand))
            {
                cand = i;
            }
        }
        
        //  Pass 2: db-check the cand
        for(int i = 0; i < n; i ++)
        {
            if(i == cand) continue;
            if(!knows(i, cand) || knows(cand, i))
                return -1;
        }
        
        return cand;
    }
};
posted on 2015-09-11 00:48  Tonix  阅读(124)  评论(0编辑  收藏  举报