7.5 leetcode

  1. P50

P50

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class :
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if x == 0:
return 0
if n == 0:
return 1
elif n > 0:
if n % 2 == 0:
return self.myPow(x * x, int(n / 2))
elif n % 2 != 0:
return x * self.myPow(x, n - 1)
else:
return 1 / self.myPow(x, -n)


x = 2
n = 10
sol = Solution()
print(sol.myPow(x, n))

按常规一个一个迭代乘法,会出现超时错误,这种对半乘的话确实快很多。

  1. P49
    P50

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

class :
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
out = {}
for s in strs:
out.setdefault(''.join(sorted(s)), []).append(s)

return list(out.values())


sol = Solution()
print(sol.groupAnagrams(['', '', 'ab']))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

class :
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
out = []
for c in strs:
count = True
for o in out:
if c == '' and c == o[0]:
o.append(c)
count = False
if len(o[0]) == len(c) and c in pailie(o[0]) and count:
o.append(c)
count = False
if count:
out.append([c])

return out


def pailie(strs):
if len(strs) == 1:
return strs
result = []
for idx, c in enumerate(strs):
result += [c + substr for substr in pailie(strs[:idx] + strs[idx + 1:])]
return result

sol = Solution()
print(sol.groupAnagrams(['aba', 'bac', 'ab']))

第二个是自己搞得(pailie函数是抄的),然后出现了超时错误,确实在全排列内块太慢了,然后看了眼discussion,发现了sorted方法,惊了个呆

  1. P47
    P47

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import itertools

nums = [1, 1, 2]

out = list(itertools.permutations(nums))
real_out = {}
for c in out:
real_out.setdefault(c)

out = list(real_out.keys())

output = []
for o in out:
output.append(list(o))
print(output)

  1. P48
    P48

1
2
3
4
5
6
7
8
9
10
11
12
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]

matrix.reverse()

for i in range(len(matrix)):
for j in range(i):
if i != j:
matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

print(matrix)

看了discussion,两个for的range,一个是len(matrix)另一个是i,小trick了