Skip to content

Commit 0c70368

Browse files
committed
no message
1 parent 0c053b4 commit 0c70368

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

problems/group-anagrams.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,23 @@ def groupAnagrams(self, strs):
1414
for c in s: hashkey[ord(c)-97] +=1
1515
anagrams[''.join(hashkey)].append(s)
1616
return anagrams.values()
17+
18+
"""
19+
Time: O(NK), N is the number of strings, K is the number of characters in the string.
20+
Space: O(NK).
21+
"""
22+
class Solution(object):
23+
def groupAnagrams(self, strs):
24+
anagrams = collections.defaultdict(list)
25+
26+
for s in strs:
27+
anagrams[self.getKey(s)].append(s)
28+
29+
return anagrams.values()
30+
31+
def getKey(self, s):
32+
key = ''
33+
counts = collections.Counter(s)
34+
for c in 'abcdefghijklmnopqrstuvwxyz':
35+
key += counts[c]*c
36+
return key

problems/ugly-number-ii.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
`ans` contains sorted ugly numbers.
3+
For each ugly number we can x2 or x3 or x5 to produce another ugly number.
4+
5+
i2 points at the number that has been x2 yet.
6+
i3 points at the number that has been x3 yet.
7+
i5 points at the number that has been x5 yet.
8+
9+
Each time we append one minimum ugly number and move the pointer.
10+
11+
Time: O(N)
12+
Space: O(N)
13+
"""
14+
class Solution(object):
15+
def nthUglyNumber(self, k):
16+
i2 = i3 = i5 = 0
17+
18+
ans = [1]
19+
while len(ans)<k:
20+
n2 = ans[i2]*2
21+
n3 = ans[i3]*3
22+
n5 = ans[i5]*5
23+
24+
n = min(n2, n3, n5)
25+
ans.append(n)
26+
27+
if n2==n: i2 += 1
28+
if n3==n: i3 += 1
29+
if n5==n: i5 += 1
30+
31+
return ans[-1]

problems/ugly-number.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution(object):
2+
def isUgly(self, n):
3+
if n<1: return False
4+
5+
while n%2==0: n /= 2
6+
while n%3==0: n /= 3
7+
while n%5==0: n /= 5
8+
9+
return n==1

0 commit comments

Comments
 (0)