diff --git a/codes/python/chapter_computational_complexity/leetcode_two_sum.py b/codes/python/chapter_computational_complexity/leetcode_two_sum.py index e1c0c848c..01c3cbcf1 100644 --- a/codes/python/chapter_computational_complexity/leetcode_two_sum.py +++ b/codes/python/chapter_computational_complexity/leetcode_two_sum.py @@ -11,6 +11,7 @@ from include import * """ 方法一:暴力枚举 """ 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: @@ -20,7 +21,9 @@ class SolutionBruteForce: """ 方法二:辅助哈希表 """ 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 diff --git a/codes/python/chapter_computational_complexity/space_complexity.py b/codes/python/chapter_computational_complexity/space_complexity.py index b4523fedb..46a234a05 100644 --- a/codes/python/chapter_computational_complexity/space_complexity.py +++ b/codes/python/chapter_computational_complexity/space_complexity.py @@ -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() @@ -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) """ 指数阶(建立满二叉树) """ diff --git a/codes/python/chapter_computational_complexity/worst_best_time_complexity.py b/codes/python/chapter_computational_complexity/worst_best_time_complexity.py index ed1a9101f..63d14ac72 100644 --- a/codes/python/chapter_computational_complexity/worst_best_time_complexity.py +++ b/codes/python/chapter_computational_complexity/worst_best_time_complexity.py @@ -10,7 +10,7 @@ from include import * """ 生成一个数组,元素为: 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) diff --git a/codes/python/chapter_sorting/merge_sort.py b/codes/python/chapter_sorting/merge_sort.py index 5fa7d83a9..437126632 100644 --- a/codes/python/chapter_sorting/merge_sort.py +++ b/codes/python/chapter_sorting/merge_sort.py @@ -8,11 +8,10 @@ import sys, os.path as osp 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]