排序算法
冒泡排序
原理:通过不断与相邻比较,交换位置,实现排序,其重复次数为排序的长度减一。
ls
= list(range(90))
random
.shuffle
(ls
)
print(ls
)
[53, 24, 22, 30, 58, 3, 83, 14, 45, 85, 43, 13, 66, 68, 63, 54, 38, 37, 86, 31, 15, 47, 17, 55, 81, 44, 84, 29, 20, 32, 5, 39, 41, 8, 35, 57, 70, 19, 2, 80, 72, 69, 76, 25, 46, 71, 28, 9, 21, 73, 88, 74, 10, 42, 6, 67, 89, 78, 18, 16, 1, 82, 40, 56, 23, 65, 50, 34, 60, 49, 48, 79, 59, 61, 12, 64, 36, 0, 11, 7, 4, 77, 52, 51, 62, 87, 75, 27, 26, 33]
def maopao(ls
):
for i
in range(len(ls
)-1):
if ls
[i
] > ls
[i
+1]:
ls
[i
],ls
[i
+1] = ls
[i
+1],ls
[i
]
else:
pass
return ls
for i
in range(len(ls
)):
maopao
(ls
)
print(ls
)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
Leetcode 遇到的问题
- 最大子数组合
暴力枚举
class Solution:
def maxSubArray(self
, nums
: List
[int]) -> int:
l
= len(nums
)
ans
= min(nums
)
for i
in range(l
):
for j
in range(i
,l
):
sums
= 0
for k
in range(i
,j
+1):
sums
+= nums
[k
]
ans
= max(ans
,sums
)
return ans
优化一个循环
class Solution:
def maxSubArray(self
, nums
: List
[int]) -> int:
l
= len(nums
)
ans
= nums
[0]
for i
in range(l
):
sums
= 0
for j
in range(i
,l
):
sums
+= nums
[j
]
ans
= max(ans
,sums
)
return ans
再优化一个循环
class Solution:
def maxSubArray(self
, nums
: List
[int]) -> int:
l
= len(nums
)
sums
= 0
ans
= nums
[0]
for i
in range(l
):
sums
+= nums
[i
]
ans
= max(ans
,sums
)
if sums
< 0:
sums
= 0
return ans
算法复杂度从n^3 到 n 的优化过程,其实是对问题的理解加深,如果能够一眼看穿问题的本质是什么就可以很快得到答案。 但有时候没有思路,也需要从复杂到简单一步步的推导。