Post

948 Sort An Array

948 Sort An Array

Sort an Array image

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:

1
2
3
4
5
**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:

1
2
3
4
5
**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
2
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
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

class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        # Base case for recursion
        if len(nums) <= 1:
            return nums
        
        # Divide the array into two halves
        mid = len(nums) // 2
        left = self.sortArray(nums[:mid])
        right = self.sortArray(nums[mid:])
        
        # Merge the two sorted halves
        return self.merge(left, right)
    
    def merge(self, left: List[int], right: List[int]) -> List[int]:
        result = []
        i = j = 0
        
        # Merge the two sorted lists into a single sorted list
        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
        
        # If there are remaining elements in left or right, append them
        result.extend(left[i:])
        result.extend(right[j:])
        
        return result




This post is licensed under CC BY 4.0 by the author.