Skip to content

Commit

Permalink
Merge branch 'youngyangyang04:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
fwqaaq authored May 27, 2023
2 parents b124152 + 5cbb991 commit 6705995
Show file tree
Hide file tree
Showing 95 changed files with 3,508 additions and 1,913 deletions.
Binary file removed .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/.DS_Store
51 changes: 49 additions & 2 deletions problems/0001.两数之和.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

那么我们就应该想到使用哈希法了。

因为本地,我们不仅要知道元素有没有遍历过,还有知道这个元素对应的下标**需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适**
因为本地,我们不仅要知道元素有没有遍历过,还要知道这个元素对应的下标**需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适**

再来看一下使用数组和set来做哈希法的局限。

Expand Down Expand Up @@ -151,7 +151,7 @@ public int[] twoSum(int[] nums, int target) {
```

Python:

(版本一) 使用字典
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
Expand All @@ -163,6 +163,53 @@ class Solution:
records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key
return []
```
(版本二)使用集合
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#创建一个集合来存储我们目前看到的数字
seen = set()
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [nums.index(complement), i]
seen.add(num)
```
(版本三)使用双指针
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 对输入列表进行排序
nums_sorted = sorted(nums)

# 使用双指针
left = 0
right = len(nums_sorted) - 1
while left < right:
current_sum = nums_sorted[left] + nums_sorted[right]
if current_sum == target:
# 如果和等于目标数,则返回两个数的下标
left_index = nums.index(nums_sorted[left])
right_index = nums.index(nums_sorted[right])
if left_index == right_index:
right_index = nums[left_index+1:].index(nums_sorted[right]) + left_index + 1
return [left_index, right_index]
elif current_sum < target:
# 如果总和小于目标,则将左侧指针向右移动
left += 1
else:
# 如果总和大于目标值,则将右指针向左移动
right -= 1
```
(版本四)暴力法
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
```

Go:

Expand Down
95 changes: 53 additions & 42 deletions problems/0015.三数之和.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,61 +298,72 @@ class Solution {
```

Python:
(版本一) 双指针
```Python
class Solution:
def threeSum(self, nums):
ans = []
n = len(nums)
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()
# 找出a + b + c = 0
# a = nums[i], b = nums[left], c = nums[right]
for i in range(n):
left = i + 1
right = n - 1
# 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了
if nums[i] > 0:
break
if i >= 1 and nums[i] == nums[i - 1]: # 去重a

for i in range(len(nums)):
# 如果第一个元素已经大于0,不需要进一步检查
if nums[i] > 0:
return result

# 跳过相同的元素以避免重复
if i > 0 and nums[i] == nums[i - 1]:
continue
while left < right:
total = nums[i] + nums[left] + nums[right]
if total > 0:
right -= 1
elif total < 0:

left = i + 1
right = len(nums) - 1

while right > left:
sum_ = nums[i] + nums[left] + nums[right]

if sum_ < 0:
left += 1
elif sum_ > 0:
right -= 1
else:
ans.append([nums[i], nums[left], nums[right]])
# 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
while left != right and nums[left] == nums[left + 1]: left += 1
while left != right and nums[right] == nums[right - 1]: right -= 1
left += 1
result.append([nums[i], nums[left], nums[right]])

# 跳过相同的元素以避免重复
while right > left and nums[right] == nums[right - 1]:
right -= 1
while right > left and nums[left] == nums[left + 1]:
left += 1

right -= 1
return ans
left += 1

return result
```
Python (v3):
(版本二) 使用字典

```python
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3: return []
nums, res = sorted(nums), []
for i in range(len(nums) - 2):
cur, l, r = nums[i], i + 1, len(nums) - 1
if res != [] and res[-1][0] == cur: continue # Drop duplicates for the first time.

while l < r:
if cur + nums[l] + nums[r] == 0:
res.append([cur, nums[l], nums[r]])
# 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.
while l < r - 1 and nums[l] == nums[l + 1]:
l += 1
while r > l + 1 and nums[r] == nums[r - 1]:
r -= 1
if cur + nums[l] + nums[r] > 0:
r -= 1
result = []
nums.sort()
# 找出a + b + c = 0
# a = nums[i], b = nums[j], c = -(a + b)
for i in range(len(nums)):
# 排序之后如果第一个元素已经大于零,那么不可能凑成三元组
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]: #三元组元素a去重
continue
d = {}
for j in range(i + 1, len(nums)):
if j > i + 2 and nums[j] == nums[j-1] == nums[j-2]: # 三元组元素b去重
continue
c = 0 - (nums[i] + nums[j])
if c in d:
result.append([nums[i], nums[j], c])
d.pop(c) # 三元组元素c去重
else:
l += 1
return res
d[nums[j]] = j
return result
```

Go:
Expand Down
2 changes: 2 additions & 0 deletions problems/0017.电话号码的字母组合.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ public:
}
};
```
* 时间复杂度: O(3^m * 4^n),其中 m 是对应四个字母的数字个数,n 是对应三个字母的数字个数
* 空间复杂度: O(3^m * 4^n)
一些写法,是把回溯的过程放在递归函数里了,例如如下代码,我可以写成这样:(注意注释中不一样的地方)
Expand Down
84 changes: 41 additions & 43 deletions problems/0018.四数之和.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,72 +207,70 @@ class Solution {
```

Python:
(版本一) 双指针
```python
# 双指针法
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:

nums.sort()
n = len(nums)
res = []
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]: continue # 对nums[i]去重
for k in range(i+1, n):
if k > i + 1 and nums[k] == nums[k-1]: continue # 对nums[k]去重
p = k + 1
q = n - 1

while p < q:
if nums[i] + nums[k] + nums[p] + nums[q] > target: q -= 1
elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1
result = []
for i in range(n):
if nums[i] > target and nums[i] > 0 and target > 0:# 剪枝(可省)
break
if i > 0 and nums[i] == nums[i-1]:# 去重
continue
for j in range(i+1, n):
if nums[i] + nums[j] > target and target > 0: #剪枝(可省)
break
if j > i+1 and nums[j] == nums[j-1]: # 去重
continue
left, right = j+1, n-1
while left < right:
s = nums[i] + nums[j] + nums[left] + nums[right]
if s == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif s < target:
left += 1
else:
res.append([nums[i], nums[k], nums[p], nums[q]])
# 对nums[p]和nums[q]去重
while p < q and nums[p] == nums[p + 1]: p += 1
while p < q and nums[q] == nums[q - 1]: q -= 1
p += 1
q -= 1
return res
right -= 1
return result

```
(版本二) 使用字典

```python
# 哈希表法
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
# use a dict to store value:showtimes
hashmap = dict()
for n in nums:
if n in hashmap:
hashmap[n] += 1
else:
hashmap[n] = 1
# 创建一个字典来存储输入列表中每个数字的频率
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1

# good thing about using python is you can use set to drop duplicates.
# 创建一个集合来存储最终答案,并遍历4个数字的所有唯一组合
ans = set()
# ans = [] # save results by list()
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
for k in range(j + 1, len(nums)):
val = target - (nums[i] + nums[j] + nums[k])
if val in hashmap:
# make sure no duplicates.
if val in freq:
# 确保没有重复
count = (nums[i] == val) + (nums[j] == val) + (nums[k] == val)
if hashmap[val] > count:
ans_tmp = tuple(sorted([nums[i], nums[j], nums[k], val]))
ans.add(ans_tmp)
# Avoiding duplication in list manner but it cause time complexity increases
# if ans_tmp not in ans:
# ans.append(ans_tmp)
else:
continue
return list(ans)
# if used list() to save results, just
# return ans
if freq[val] > count:
ans.add(tuple(sorted([nums[i], nums[j], nums[k], val])))

return [list(x) for x in ans]

```

Go:
Expand Down
28 changes: 18 additions & 10 deletions problems/0019.删除链表的倒数第N个节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,29 @@ Python:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
head_dummy = ListNode()
head_dummy.next = head

slow, fast = head_dummy, head_dummy
while(n>=0): #fast先往前走n+1步
# 创建一个虚拟节点,并将其下一个指针设置为链表的头部
dummy_head = ListNode(0, head)

# 创建两个指针,慢指针和快指针,并将它们初始化为虚拟节点
slow = fast = dummy_head

# 快指针比慢指针快 n+1 步
for i in range(n+1):
fast = fast.next
n -= 1
while(fast!=None):

# 移动两个指针,直到快速指针到达链表的末尾
while fast:
slow = slow.next
fast = fast.next
#fast 走到结尾后,slow的下一个节点为倒数第N个节点
slow.next = slow.next.next #删除
return head_dummy.next

# 通过更新第 (n-1) 个节点的 next 指针删除第 n 个节点
slow.next = slow.next.next

return dummy_head.next

```
Go:
```Go
Expand Down
23 changes: 11 additions & 12 deletions problems/0024.两两交换链表中的节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,21 +186,20 @@ Python:

class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
res = ListNode(next=head)
pre = res
dummy_head = ListNode(next=head)
current = dummy_head

# 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了
while pre.next and pre.next.next:
cur = pre.next
post = pre.next.next
# 必须有cur的下一个和下下个才能交换,否则说明已经交换结束了
while current.next and current.next.next:
temp = current.next # 防止节点修改
temp1 = current.next.next.next

# pre,cur,post对应最左,中间的,最右边的节点
cur.next = post.next
post.next = cur
pre.next = post
current.next = current.next.next
current.next.next = temp
temp.next = temp1
current = current.next.next
return dummy_head.next

pre = pre.next.next
return res.next
```

Go:
Expand Down
Loading

0 comments on commit 6705995

Please sign in to comment.