Update Python codes.

pull/341/head
krahets 2 years ago
parent 4655534bd6
commit 1b0a3a6e69

@ -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

@ -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)
""" 指数阶(建立满二叉树) """

@ -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)

@ -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]

Loading…
Cancel
Save