mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-03 22:41:58 +00:00
添加了python版本代码
为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
@@ -128,6 +128,8 @@ temp[8] = 5。然后再将 presum[5] 减 1 。
|
||||
|
||||
一样可以,哦了,到这里我们就搞定了计数排序,下面我们来看一哈代码吧。
|
||||
|
||||
Java Code:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int[] sortArray(int[] nums) {
|
||||
@@ -169,6 +171,44 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
Python Code:
|
||||
|
||||
```python
|
||||
from typing import List
|
||||
class Solution:
|
||||
def sortArray(self,nums: List[int])->List[int]:
|
||||
leng = len(nums)
|
||||
if leng < 1:
|
||||
return nums
|
||||
# 求出最大最小值
|
||||
max = nums[0]
|
||||
min = nums[0]
|
||||
for x in nums:
|
||||
if max < x:
|
||||
max = x
|
||||
if min > x:
|
||||
min = x
|
||||
# 设置 presum 数组长度,然后求出我们的前缀和数组,
|
||||
# 这里我们可以把求次数数组和前缀和数组用一个数组处理
|
||||
presum = [0] * (max - min + 1)
|
||||
for x in nums:
|
||||
presum[x - min] += 1
|
||||
for i in range(1, len(presum)):
|
||||
presum[i] = presum[i - 1] + presum[i]
|
||||
# 临时数组
|
||||
temp = [0] * leng
|
||||
# 遍历数组,开始排序,注意偏移量
|
||||
for i in range(leng - 1, -1, -1):
|
||||
# 查找 presum 字典,然后将其放到临时数组,注意偏移度
|
||||
index = presum[nums[i] - min] - 1
|
||||
temp[index] = nums[i]
|
||||
# 相应位置减一
|
||||
presum[nums[i] - min] -= 1
|
||||
# copy回原数组
|
||||
nums = temp
|
||||
return nums
|
||||
```
|
||||
|
||||
好啦,这个排序算法我们已经搞定了,下面我们来扒一扒它。
|
||||
|
||||
**计数排序时间复杂度分析**
|
||||
|
Reference in New Issue
Block a user