forked from itcharge/LeetCode-Py
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
18 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,26 @@ | ||
class Solution: | ||
def radixSort(self, arr): | ||
def radixSort(self, nums: [int]) -> [int]: | ||
# 桶的大小为所有元素的最大位数 | ||
size = len(str(max(arr))) | ||
|
||
# 从低位到高位依次遍历每一位,以各个数位值为索引,对数组进行按数位排序 | ||
size = len(str(max(nums))) | ||
# 从最低位(个位)开始,逐位遍历每一位 | ||
for i in range(size): | ||
# 使用一个长度为 10 的桶来存放各个位上的元素 | ||
# 定义个数为 10 的桶数组 buckets,每个桶分别代表 0 ~ 9 中的 1 个数字。 | ||
buckets = [[] for _ in range(10)] | ||
# 遍历数组元素,根据元素对应位上的值,将其存入对应位的桶中 | ||
for num in arr: | ||
# 遍历数组元素,按照每个元素当前位上的数字,将元素放入对应数字的桶中。 | ||
for num in nums: | ||
buckets[num // (10 ** i) % 10].append(num) | ||
# 清空原始数组 | ||
arr.clear() | ||
# 从桶中依次取出对应元素,并重新加入到原始数组 | ||
nums.clear() | ||
# 按照桶的顺序依次取出对应元素,重新加入到原始数组中。 | ||
for bucket in buckets: | ||
for num in bucket: | ||
arr.append(num) | ||
|
||
return arr | ||
|
||
def sortArray(self, nums: List[int]) -> List[int]: | ||
return self.radixSort(nums) | ||
nums.append(num) | ||
|
||
# 完成排序,返回结果数组 | ||
return nums | ||
|
||
def sortArray(self, nums: [int]) -> [int]: | ||
return self.radixSort(nums) | ||
|
||
print(Solution().sortArray([692, 924, 969, 503, 871, 704, 542, 436])) |