注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
最近在刷leetcode,屡次发现了自己同样的算法,在最后的排行榜中比别人低,不知道有没有大佬可以解惑?
一个例子: 这个例子比较明显,今天的每日一题任务中:Find the town Judge
题目:
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
不一定是最优解,但是也是beat 90%以上的解法: 时间744ms
- def findJudge(self, N: int, trust: List[List[int]]) -> int:
- society_level = [0 for i in range(N)]
- suspicion_level = [0 for i in range(N)]
- for el in trust:
- society_level[el[1] - 1] += 1
- suspicion_level[el[0] - 1] += 1
- for i in range(N):
- if society_level[i] == N - 1:
- if suspicion_level[i] == 0:
- return i + 1
- return -1
复制代码
然后我的解法几乎和他一样,然后后续做了微弱改动和他一样了,但是需要1000ms:
- first = [0 for k in range(N)]
- second = [0 for k in range(N)]
- for i in trust:
- first[i[0]-1] += 1
- second[i[1]-1] += 1
- for j in range(N):
- if first[j] == 0 and second[j] == N-1:#he trust nobody and he got N-1 trust
- return j+1
- return -1
复制代码
不太明白~~理论上,同样的代码都是给leetcode的服务器来跑,所以应该是一样的时间吧? 还是说这个取决于生成了不同的test case?
|