-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path63_median.java
55 lines (51 loc) · 1.48 KB
/
63_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
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
if(nums==null||nums.length==0)
return 0;
int len = nums.length;
int low = 0;
int high = len-1;
int parIndex = partition(nums,low,high);
int index = getIndex(len);
while(parIndex!=index){
System.out.println(parIndex);
if(parIndex<index)
parIndex = partition(nums,parIndex+1,high);
else if(parIndex>index)
parIndex = partition(nums,low,parIndex-1);
}
return nums[index];
}
public int getIndex(int num){
if(num%2==0)
return num/2-1;
return num/2;
}
public int partition(int[] array,int low,int high){
int lowFlag = low;
int highFlag = high+1;
while(true){
while(array[++lowFlag]<=array[low]) if(lowFlag==high)break;
while(array[--highFlag]>=array[low]) if(highFlag==low)break;
if(lowFlag>=highFlag) break;
exch(array,lowFlag,highFlag);
}
exch(array,low,highFlag);
return highFlag;
}
private void exch(int[] array,int i,int j){
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static void main(String[]args){
Solution s = new Solution();
int[] array = {4,5,1,2,3};
s.median(array);
}
}