forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKthSmallestNumbersinUnsortedArray.java
45 lines (38 loc) · 1.15 KB
/
KthSmallestNumbersinUnsortedArray.java
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
class Solution {
/*
* @param k an integer
* @param nums an integer array
* @return kth smallest element
*/
public int kthSmallest(int k, int[] nums) {
// write your code here
return quickSelect(nums, 0, nums.length - 1, k - 1);
}
public int quickSelect(int[] A, int start, int end , int k) {
if (start == end)
return A[start];
int left = start, right = end;
int pivot = A[(start + end) / 2];
while (left <= right) {
while (left <= right && A[left] < pivot) {
left++;
}
while (left <= right && A[right] > pivot) {
right--;
}
if (left <= right) {
int temp = A[left];
A[left] = A[right];
A[right] = temp;
left++;
right--;
}
}
if (right >= k && start <= right)
return quickSelect(A, start, right, k);
else if (left <= k && left <= end)
return quickSelect(A, left, end, k);
else
return A[k];
}
};