Merge branch 'youngyangyang04:master' into master

This commit is contained in:
fusunx
2021-06-15 18:53:40 -05:00
5 changed files with 75 additions and 6 deletions

View File

@ -107,7 +107,7 @@ public int[] twoSum(int[] nums, int target) {
Python
```python3
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap={}

View File

@ -118,7 +118,7 @@ class Solution {
```
Python
```python3
```python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
result_set = set()

View File

@ -135,8 +135,52 @@ class Solution {
```
Python
```py
Python写法一(使用数组作为哈希表)
```python
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
arr = [0] * 26
for x in magazine:
arr[ord(x) - ord('a')] += 1
for x in ransomNote:
if arr[ord(x) - ord('a')] == 0:
return False
else:
arr[ord(x) - ord('a')] -= 1
return True
```
Python写法二使用defaultdict
```python
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
from collections import defaultdict
hashmap = defaultdict(int)
for x in magazine:
hashmap[x] += 1
for x in ransomNote:
value = hashmap.get(x)
if value is None or value == 0:
return False
else:
hashmap[x] -= 1
return True
```
Python写法三
```python
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
@ -166,6 +210,7 @@ class Solution(object):
```
Go
```go
func canConstruct(ransomNote string, magazine string) bool {
record := make([]int, 26)

View File

@ -120,7 +120,7 @@ class Solution {
Python
```
```python
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
"""
@ -147,7 +147,31 @@ class Solution(object):
if key in hashmap:
count += hashmap[key]
return count
# 下面这个写法更为简洁,但是表达的是同样的算法
# class Solution:
# def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
# from collections import defaultdict
# hashmap = defaultdict(int)
# for x1 in nums1:
# for x2 in nums2:
# hashmap[x1+x2] += 1
# count=0
# for x3 in nums3:
# for x4 in nums4:
# key = -x3-x4
# value = hashmap.get(key)
# dict的get方法会返回Nonekey不存在或者key对应的value
# 所以如果value==0就会继续执行orcount+0否则就会直接加value
# 这样就不用去写if判断了
# count += value or 0
# return count
```

View File

@ -340,7 +340,7 @@ class MyLinkedList {
```
Python
```python3
```python
# 单链表
class Node: