原题链接在这里:https://leetcode.com/problems/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
题解:
Use quick sort and get result.
Time Complexity: O(nlogn).
Space: O(logn). stack space.
AC Java:
1 class Solution { 2 public List<Integer> sortArray(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 8 quickSort(nums, 0, nums.length - 1); 9 for(int num : nums){ 10 res.add(num); 11 } 12 13 return res; 14 } 15 16 private void quickSort(int [] nums, int l, int r){ 17 if(l >= r){ 18 return; 19 } 20 21 int m = partition(nums, l, r); 22 quickSort(nums, l, m); 23 quickSort(nums, m + 1, r); 24 } 25 26 private int partition(int [] nums, int l, int r){ 27 int pivot = nums[l]; 28 while(l < r){ 29 while(l < r && nums[r] >= pivot){ 30 r--; 31 } 32 33 nums[l] = nums[r]; 34 35 while(l < r && nums[l] <= pivot){ 36 l++; 37 } 38 39 nums[r] = nums[l]; 40 } 41 42 nums[l] = pivot; 43 return l; 44 } 45 }