912. Sort an Array

Medium (Trung bình) Python 🔗 Xem trên LeetCode

📋 Đề Bài

Given an array of integers nums, sort the array in ascending order and return it.

You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.

 

Example 1:

Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).

Example 2:

Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Explanation: Note that the values of nums are not necessairly unique.

 

Constraints:

  • 1 <= nums.length <= 5 * 104
  • -5 * 104 <= nums[i] <= 5 * 104

🧠 Thuật Toán & Kỹ Thuật

Binary Search (Tìm kiếm nhị phân)Divide and Conquer (Chia để trị)
⏱️ Thời gian O(log n)
💾 Không gian O(n)

💻 Lời Giải

Python 0912-sort-an-array.py
class Solution:
    def mergeSort(self, nums: List[int]) -> None:
        if len(nums) <= 1:
            return
        
        mid = len(nums) // 2
        nums1 = nums[:mid]
        nums2 = nums[mid:]

        self.mergeSort(nums1)
        self.mergeSort(nums2)

        i = j = k = 0
        n, m = len(nums1), len(nums2)

        while i < n and j < m:
            if nums1[i] < nums2[j]:
                nums[k] = nums1[i]
                i += 1
            else:
                nums[k] = nums2[j]
                j += 1
            k += 1
            
        while i < n:
            nums[k] = nums1[i]
            i += 1
            k += 1
            
        while j < m:
            nums[k] = nums2[j]
            j += 1
            k += 1
                
    def sortArray(self, nums: List[int]) -> List[int]:
        self.mergeSort(nums)
        return nums