我的個人微信公衆號:Microstrong
微信公衆號ID:MicrostrongAI
微信公衆號介紹:Microstrong(小強)同學主要研究機器學習、深度學習、計算機視覺、智能對話系統相關內容,分享在學習過程中的讀書筆記!期待您的關注,歡迎一起學習交流進步!
知乎主頁:https://www.zhihu.com/people/MicrostrongAI/activities
912. Sort an Array
Given an array of integers nums
, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1] Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5]
Constraints:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
解題思路:
(1)快速排序
已經AC的代碼:
from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
low = 0
high = len(nums) - 1
if low < high:
self.QSort(nums, low, high)
return nums
def QSort(self, nums, low, high):
if low < high:
index = self.Partition(nums, low, high)
self.QSort(nums, low, index - 1)
self.QSort(nums, index + 1, high)
def Partition(self, nums, low, high):
pivotkey = nums[low]
while low < high:
while low < high and nums[high] >= pivotkey:
high -= 1
nums[low] = nums[high]
while low < high and nums[low] < pivotkey:
low += 1
nums[high] = nums[low]
nums[low] = pivotkey
return high
if __name__ == "__main__":
# nums = [5, 2, 3, 1]
nums = [5, 1, 1, 2, 0, 0]
sol = Solution()
print(sol.sortArray(nums))