[LeetCode] 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]

排序数组。很直白的一道题,就是给数组按升序重新排序。这里我用quicksort实现。

时间O(nlogn), worst case O(n^2)

空间O(1)

Java实现

 1 class Solution {
 2     public int[] sortArray(int[] nums) {
 3         quickSort(nums, 0, nums.length - 1);
 4         int[] res = new int[nums.length];
 5         for (int i = 0; i < nums.length; i++) {
 6             res[i] = nums[i];
 7         }
 8         return res;
 9     }
10 
11     public static void quickSort(int nums[], int left, int right) {
12         if (left >= right) {
13             return;
14         }
15         int mid = partition(nums, left, right);
16         quickSort(nums, left, mid);
17         quickSort(nums, mid + 1, right);
18     }
19 
20     public static void swap(int[] nums, int left, int right) {
21         int temp = nums[left];
22         nums[left] = nums[right];
23         nums[right] = temp;
24     }
25 
26     public static int partition(int[] nums, int left, int right) {
27         int pivot = nums[left];
28         while (left < right) {
29             while (left < right && nums[right] >= pivot) {
30                 right--;
31             }
32             swap(nums, left, right);
33             while (left < right && nums[left] <= pivot) {
34                 left++;
35             }
36             swap(nums, right, left);
37         }
38         nums[left] = pivot;
39         return left;
40     }
41 }

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[]}
 4  */
 5 var sortArray = function(nums) {
 6     return quickSort(nums, 0, nums.length - 1);
 7 };
 8 
 9 const quickSort = function(arr, left, right) {
10     let index;
11     if (arr.length > 1) {
12         index = partition(arr, left, right);
13         if (left < index - 1) {
14             quickSort(arr, left, index - 1);
15         }
16         if (right > index) {
17             quickSort(arr, index, right);
18         }
19     }
20     return arr;
21 };
22 
23 const partition = function(arr, left, right) {
24     const pivot = arr[Math.floor((left + right) / 2)];
25     let i = left;
26     let j = right;
27     while (i <= j) {
28         while (arr[i] < pivot) {
29             i++;
30         }
31         while (arr[j] > pivot) {
32             j--;
33         }
34         if (i <= j) {
35             swap(arr, i, j);
36             i++;
37             j--;
38         }
39     }
40     return i;
41 };
42 
43 const swap = function(arr, i, j) {
44     const temp = arr[i];
45     arr[i] = arr[j];
46     arr[j] = temp;
47 };

相关题目

215. Kth Largest Element in an Array

912. Sort an Array

973. K Closest Points to Origin

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12602653.html