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
| import random
def swap(nums, a, b): if a == b or nums[a] == nums[b]: return tmp = nums[a] nums[a] = nums[b] nums[b] = tmp
def partition(nums, start, end): p = start - 1 q = start r = random.randint(start, end) swap(nums, r, end) while q < end: if nums[q] < nums[end]: p += 1 swap(nums, p, q) q += 1 p += 1 swap(nums, p, q) return p
def quickSort(nums, start, end): if (start < end): i = partition(nums, start, end) idx = i - 1 while start <= idx <= end and nums[idx] == nums[i]: idx -= 1 quickSort(nums, start, idx) idx = i + 1 while start <= idx <= end and nums[idx] == nums[i]: idx += 1 quickSort(nums, idx, end)
class Solution: def sortArray(self, nums: List[int]) -> List[int]: quickSort(nums, 0, len(nums) - 1) return nums
|