Skip to content

Commit

Permalink
Update Python codes.
Browse files Browse the repository at this point in the history
  • Loading branch information
krahets committed Feb 5, 2023
1 parent 4655534 commit 1b0a3a6
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
""" 方法一:暴力枚举 """
class SolutionBruteForce:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 两层循环,时间复杂度 O(n^2)
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
Expand All @@ -20,7 +21,9 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
""" 方法二:辅助哈希表 """
class SolutionHashMap:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 辅助哈希表,空间复杂度 O(n)
dic = {}
# 单层循环,时间复杂度 O(n)
for i in range(len(nums)):
if target - nums[i] in dic:
return dic[target - nums[i]], i
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def constant(n):
node = ListNode(0)
# 循环中的变量占用 O(1) 空间
for _ in range(n):
c = 0
c = 0
# 循环中的函数占用 O(1) 空间
for _ in range(n):
function()
Expand Down Expand Up @@ -49,8 +49,8 @@ def quadratic(n):
""" 平方阶(递归实现) """
def quadratic_recur(n):
if n <= 0: return 0
# 数组 nums 长度为 n, n-1, ..., 2, 1
nums = [0] * n
print("递归 n =", n, "中的 nums 长度 =", len(nums))
return quadratic_recur(n - 1)

""" 指数阶(建立满二叉树) """
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

""" 生成一个数组,元素为: 1, 2, ..., n ,顺序被打乱 """
def random_numbers(n):
# 生成数组 nums =: 1, 2, 3, ..., n
# 生成数组 nums =: 1, 2, 3, ..., n
nums = [i for i in range(1, n + 1)]
# 随机打乱数组元素
random.shuffle(nums)
Expand Down
9 changes: 4 additions & 5 deletions codes/python/chapter_sorting/merge_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *

"""
合并左子数组和右子数组
左子数组区间 [left, mid]
右子数组区间 [mid + 1, right]
"""

""" 合并左子数组和右子数组 """
# 左子数组区间 [left, mid]
# 右子数组区间 [mid + 1, right]
def merge(nums, left, mid, right):
# 初始化辅助数组 借助 copy模块
tmp = nums[left:right + 1]
Expand Down

0 comments on commit 1b0a3a6

Please sign in to comment.