Skip to content

Commit 40333fd

Browse files
authored
Create the-number-of-weak-characters-in-the-game.py
1 parent 84a5316 commit 40333fd

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Time: O(nlogn)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def numberOfWeakCharacters(self, properties):
6+
"""
7+
:type properties: List[List[int]]
8+
:rtype: int
9+
"""
10+
properties.sort(cmp=lambda a, b: cmp(b[1], a[1]) if a[0] == b[0] else cmp(a[0], b[0]))
11+
result = max_d = 0
12+
for a, d in reversed(properties):
13+
if d < max_d:
14+
result += 1
15+
max_d = max(max_d, d)
16+
return result
17+
18+
19+
# Time: O(nlogn)
20+
# Space: O(n)
21+
import collections
22+
23+
24+
# faster in sort by using more space
25+
class Solution(object):
26+
def numberOfWeakCharacters(self, properties):
27+
"""
28+
:type properties: List[List[int]]
29+
:rtype: int
30+
"""
31+
lookup = collections.defaultdict(list)
32+
for a, d in properties:
33+
lookup[a].append(d)
34+
result = max_d = 0
35+
for a in sorted(lookup.iterkeys(), reverse=True):
36+
result += sum(d < max_d for d in lookup[a])
37+
max_d = max(max_d, max(lookup[a]))
38+
return result

0 commit comments

Comments
 (0)