Skip to content

Commit cce8741

Browse files
Merge pull request youngyangyang04#1117 from Camille0512/master
Added in one more python solution. Using defaultdict.
2 parents 1900e4f + 6e3f394 commit cce8741

File tree

7 files changed

+154
-0
lines changed

7 files changed

+154
-0
lines changed

problems/0001.两数之和.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ class Solution:
118118
return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
119119
```
120120

121+
Python (v2):
122+
123+
```python
124+
class Solution:
125+
def twoSum(self, nums: List[int], target: int) -> List[int]:
126+
rec = {}
127+
for i in range(len(nums)):
128+
rest = target - nums[i]
129+
# Use get to get the index of the data, making use of one of the dictionary properties.
130+
if rec.get(rest, None) is not None: return [rec[rest], i]
131+
rec[nums[i]] = i
132+
```
121133

122134
Go:
123135

problems/0015.三数之和.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,34 @@ class Solution:
247247
right -= 1
248248
return ans
249249
```
250+
Python (v2):
251+
252+
```python
253+
class Solution:
254+
def threeSum(self, nums: List[int]) -> List[List[int]]:
255+
if len(nums) < 3: return []
256+
nums, res = sorted(nums), []
257+
for i in range(len(nums) - 2):
258+
cur, l, r = nums[i], i + 1, len(nums) - 1
259+
if res != [] and res[-1][0] == cur: continue # Drop duplicates for the first time.
260+
261+
while l < r:
262+
if cur + nums[l] + nums[r] == 0:
263+
res.append([cur, nums[l], nums[r]])
264+
# Drop duplicates for the second time in interation of l & r. Only used when target situation occurs, because that is the reason for dropping duplicates.
265+
while l < r - 1 and nums[l] == nums[l + 1]:
266+
l += 1
267+
while r > l + 1 and nums[r] == nums[r - 1]:
268+
r -= 1
269+
if cur + nums[l] + nums[r] > 0:
270+
r -= 1
271+
else:
272+
l += 1
273+
return res
274+
```
275+
250276
Go:
277+
251278
```Go
252279
func threeSum(nums []int)[][]int{
253280
sort.Ints(nums)

problems/0101.对称二叉树.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,41 @@ class Solution:
437437
return True
438438
```
439439

440+
层序遍历
441+
442+
```python
443+
class Solution:
444+
def isSymmetric(self, root: TreeNode) -> bool:
445+
if not root: return True
446+
que, cnt = [[root.left, root.right]], 1
447+
while que:
448+
nodes, tmp, sign = que.pop(), [], False
449+
for node in nodes:
450+
if not node:
451+
tmp.append(None)
452+
tmp.append(None)
453+
else:
454+
if node.left:
455+
tmp.append(node.left)
456+
sign = True
457+
else:
458+
tmp.append(None)
459+
if node.right:
460+
tmp.append(node.right)
461+
sign = True
462+
else:
463+
tmp.append(None)
464+
p1, p2 = 0, len(nodes) - 1
465+
while p1 < p2:
466+
if (not nodes[p1] and nodes[p2]) or (nodes[p1] and not nodes[p2]): return False
467+
elif nodes[p1] and nodes[p2] and nodes[p1].val != nodes[p2].val: return False
468+
p1 += 1
469+
p2 -= 1
470+
if sign: que.append(tmp)
471+
cnt += 1
472+
return True
473+
```
474+
440475
## Go
441476

442477
```go

problems/0151.翻转字符串里的单词.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,38 @@ class Solution:
438438

439439
```
440440

441+
```python
442+
class Solution:
443+
def reverseWords(self, s: str) -> str:
444+
# method 1 - Rude but work & efficient method.
445+
s_list = [i for i in s.split(" ") if len(i) > 0]
446+
return " ".join(s_list[::-1])
447+
448+
# method 2 - Carlo's idea
449+
def trim_head_tail_space(ss: str):
450+
p = 0
451+
while p < len(ss) and ss[p] == " ":
452+
p += 1
453+
return ss[p:]
454+
455+
# Trim the head and tail space
456+
s = trim_head_tail_space(s)
457+
s = trim_head_tail_space(s[::-1])[::-1]
458+
459+
pf, ps, s = 0, 0, s[::-1] # Reverse the string.
460+
while pf < len(s):
461+
if s[pf] == " ":
462+
# Will not excede. Because we have clean the tail space.
463+
if s[pf] == s[pf + 1]:
464+
s = s[:pf] + s[pf + 1:]
465+
continue
466+
else:
467+
s = s[:ps] + s[ps: pf][::-1] + s[pf:]
468+
ps, pf = pf + 1, pf + 2
469+
else:
470+
pf += 1
471+
return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions,
472+
```
441473

442474
Go:
443475

problems/0454.四数相加II.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,24 @@ class Solution(object):
141141

142142
```
143143

144+
```python
145+
class Solution:
146+
def fourSumCount(self, nums1: list, nums2: list, nums3: list, nums4: list) -> int:
147+
from collections import defaultdict # You may use normal dict instead.
148+
rec, cnt = defaultdict(lambda : 0), 0
149+
# To store the summary of all the possible combinations of nums1 & nums2, together with their frequencies.
150+
for i in nums1:
151+
for j in nums2:
152+
rec[i+j] += 1
153+
# To add up the frequencies if the corresponding value occurs in the dictionary
154+
for i in nums3:
155+
for j in nums4:
156+
cnt += rec.get(-(i+j), 0) # No matched key, return 0.
157+
return cnt
158+
```
159+
144160
Go:
161+
145162
```go
146163
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
147164
m := make(map[int]int)

problems/0541.反转字符串II.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,23 @@ class Solution:
227227
return ''.join(res)
228228
```
229229

230+
Python3 (v2):
231+
232+
```python
233+
class Solution:
234+
def reverseStr(self, s: str, k: int) -> str:
235+
# Two pointers. Another is inside the loop.
236+
p = 0
237+
while p < len(s):
238+
p2 = p + k
239+
# Written in this could be more pythonic.
240+
s = s[:p] + s[p: p2][::-1] + s[p2:]
241+
p = p + 2 * k
242+
return s
243+
```
230244

231245
Go:
246+
232247
```go
233248
func reverseStr(s string, k int) string {
234249
ss := []byte(s)

problems/剑指Offer05.替换空格.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,8 +291,24 @@ class Solution:
291291

292292
```
293293

294+
```python
295+
class Solution:
296+
def replaceSpace(self, s: str) -> str:
297+
# method 1 - Very rude
298+
return "%20".join(s.split(" "))
299+
300+
# method 2 - Reverse the s when counting in for loop, then update from the end.
301+
n = len(s)
302+
for e, i in enumerate(s[::-1]):
303+
print(i, e)
304+
if i == " ":
305+
s = s[: n - (e + 1)] + "%20" + s[n - e:]
306+
print("")
307+
return s
308+
```
294309

295310
javaScript:
311+
296312
```js
297313
/**
298314
* @param {string} s

0 commit comments

Comments
 (0)