Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为LeetCode第437、455题增加了Python语言支持 #520

Merged
merged 11 commits into from
Jan 20, 2022
36 changes: 35 additions & 1 deletion problems/437.path-sum-iii.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,9 @@ var pathSum = function (root, sum) {

## 代码

- 语言支持:JS
- 语言支持:JS, Python

JS code:
```js
/*
* @lc app=leetcode id=437 lang=javascript
Expand Down Expand Up @@ -164,6 +165,39 @@ var pathSum = function (root, sum) {
};
```

Python Code:
```python
import collections
'''
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
'''
class Solution:
def helper(self,root,acc,target,hashmap):
if not root:
return 0
count=0
acc+=root.val
if acc==target:
count+=1
if acc-target in hashmap:
count+=hashmap[acc-target]
hashmap[acc]+=1
if root.left:
count+=self.helper(root.left,acc,target,hashmap)
if root.right:
count+=self.helper(root.right,acc,target,hashmap)
hashmap[acc]-=1
return count

def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
hashmap=collections.defaultdict(lambda:0)
return self.helper(root,0,targetSum,hashmap)
```

**复杂度分析**

- 时间复杂度:$O(N)$
Expand Down
18 changes: 17 additions & 1 deletion problems/455.AssignCookies.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ https://leetcode-cn.com/problems/assign-cookies/

## 代码

语言支持:JS
语言支持:JS, Python

JS Code:
```js
/**
* @param {number[]} g
Expand Down Expand Up @@ -90,6 +91,21 @@ const findContentChildren = function (g, s) {
};
```

Python Code:
```python
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
count=gIdx=sIdx=0
while gIdx<len(g) and sIdx<len(s):
if s[sIdx]>=g[gIdx]:
gIdx+=1
count+=1
sIdx+=1
return count
```

***复杂度分析***

- 时间复杂度:由于使用了排序,因此时间复杂度为 O(NlogN)
Expand Down