-
Notifications
You must be signed in to change notification settings - Fork 15
/
median.java
65 lines (59 loc) · 1.82 KB
/
median.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class Solution {
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
public int median(int[] nums) {
// write your code here
int len = nums.length;
if (len == 0) {
return 0;
}
// quick select mid-th element.
int medianIndex = (len % 2 == 0)? len / 2 - 1 : len / 2;
int start = 0;
int end = len - 1;
//
while (start <= end) {
int mid = (start + end) / 2;
int relocate = partition(nums, start, end, mid);
if (medianIndex == relocate) {
return nums[medianIndex];
} else if (relocate > medianIndex) {
end = relocate - 1;
} else {
start = relocate + 1;
}
}
return 0;
}
public int partition(int[] nums, int start, int end, int pivot) {
// return the right index of pivotal
int pivotal = nums[pivot];
swap(nums, end, pivot);
int storedIndex = start;
for (int i = start; i < end; i++) {
if (nums[i] < pivotal) {
swap(nums, i, storedIndex++);
// 4 9 8 5 1 6 3 : pivotal is 5
// 4 9 8 3 1 6 5
// dot denotes the value of storedIndex.
// 4 .
// 4 9.
// 4 9. 8
// 4 3 8. 9
// 4 3 1 9. 8
// 4 3 1 9. 8 6
// 4 3 1 9. 8 6 5
// 4 3 1 5. 8 6 9
}
}
swap(nums, storedIndex, end);
return storedIndex;
}
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}