【LeetCode】912. Sort an Array

我的个人微信公众号:Microstrong

微信公众号ID:MicrostrongAI

微信公众号介绍:Microstrong(小强)同学主要研究机器学习、深度学习、计算机视觉、智能对话系统相关内容,分享在学习过程中的读书笔记!期待您的关注,欢迎一起学习交流进步!

知乎主页:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

个人博客:https://blog.csdn.net/program_developer

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))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章