lintcode Median

给定一个未排序的整数数组,找到其中位数。

中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。

样例
给出数组[4, 5, 1, 2, 3], 返回 3

给出数组[7, 9, 4, 5],返回 5

挑战
时间复杂度为O(n)

与求第k大数思路一样,利用快速排序的分治思想,快速排序时间复杂度为O(nlogn),此题要求O(n),因此每次只需对一半数据进行排序,这里不再证明。

public class Solution{
	public int median(int[] nums){
        if (nums == null || nums.length == 0) {
            return -1;
        }
		int len=nums.length;
		if(len%2==0){
			return search(nums,len/2,0,len-1);
		}
		else{
			return search(nums,len/2+1,0,len-1);
		}
		
	
	
	public int search(int[] nums, int k, int start, int end){
		int L=start,R=end;
		int pivot=R;//就是都是与最后一个值比的
		
		while(true){
			while(nums[L]<nums[pivot]&&L<R){
				L++;
			}
			while(nums[R]<nums[pivot]&&L<R){
				R--}
			if(L==R){//记的是==
				break;
			}
			swap(nums,L,R);
		}
		swap(nums,L,end);
	    if(k==L+1){//这里L相当于是中点,习惯上就是 start,l-1   l  l+l,end
		    return nums[L];
	    }else if(k>L+1){
		    return search(nums,k,L+1,end);
	    }else{
		    return seach(nums,k,start,L-1);
	}
	
	public void swap(int[] nums, int l,int r){
		int temp=nums[l];
		int[l]=nums[r];
		int[r]=temp;
	}
}
发布了54 篇原创文章 · 获赞 2 · 访问量 712

猜你喜欢

转载自blog.csdn.net/qq_40647378/article/details/104058185
今日推荐