-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortanArray.java
More file actions
64 lines (57 loc) · 1.33 KB
/
SortanArray.java
File metadata and controls
64 lines (57 loc) · 1.33 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package medium;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* ClassName: SortanArray.java
* Author: chenyiAlone
* Create Time: 2019/12/23 20:48
* Description: No.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
*
*/
public class SortanArray {
private Random rand = new Random();
private void sort(int l, int r, int[] nums) {
if (l >= r) return;
int axie = l + rand.nextInt(r - l + 1);
int L = l, R = r, pivot = nums[axie];
while (L <= R) {
while (L <= R && nums[L] < pivot) L++;
while (L <= R && nums[R] > pivot) R--;
if (L <= R) {
int t = nums[L];
nums[L] = nums[R];
nums[R] = t;
L++; R--;
}
}
sort(l, R, nums);
sort(L, r, nums);
}
public List<Integer> sortArray(int[] nums) {
sort(0, nums.length - 1, nums);
List<Integer> ret = new LinkedList<>();
for (int i : nums)
ret.add(i);
return ret;
}
}