【简单】Lintcode 80:Median

本文介绍两种寻找未排序整数数组中位数的方法:一种是直接排序后取中位数;另一种是利用快速排序的特性来高效查找中位数,后者避免了完全排序,提高了查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a unsorted array with integers, find the median of it.

A median is the middle number of the array after it is sorted.

If there are even numbers in the array, return the N/2-th number after sorted.

Example

Given [4, 5, 1, 2, 3], return 3.

Given [7, 9, 4, 5], return 5.

第一种方法:

直接先排序后取中位数,思路很简单,但是时间复杂度稍高。

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: An integer denotes the middle number of the array
     */
    int median(vector<int> &nums) {
        // write your code here
        int n = nums.size();
        sort(nums.begin(),nums.end());
        return nums[(n-1)/2];
    }
};

第二种方法:

利用快速排序的特性,由于每次快排partition操作后,总有一个元素被放置在排好序后的正确位置p,通过检测这个元素是否为中位数(p == nums.size()-1/2),若是直接返回,若不是则在中位数本应该在的区间继续进行快排,直到找到这个中位数。这样就只是对少量元素进行排序就找到了中位数,不需要全部遍历。
class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: An integer denotes the middle number of the array
     */
    int median(vector<int> &nums) {
        // write your code here
        return quickSort(nums, 0, nums.size()-1);
    }
    
    int partition(vector<int> &nums, int l, int r)//返回p,使得nums[l...p-l] < nums[p] ; nums[p+1...r] > nums[p]
    {
    	int v = nums[l];
    	int j = l;
    	int i = j + 1;
    
    	for (; i <= r; i++)
    	{
    		if (nums[i] < v)
    		{
    			swap(nums[j+1], nums[i]);
    			j++;
    		}
    	}
    	swap(nums[l], nums[j]); 
    	return j;
    }

    int quickSort(vector<int> &nums, int l, int r)//对nums[l...r]部分进行快速排序
    {
    	int p = partition(nums, l, r);
    	
    	if (p == (nums.size() - 1) / 2)
    		return nums[p];
    	else if(p > (nums.size() - 1) / 2)
    		quickSort(nums, l, p - 1);
    	else 
    		quickSort(nums, p+1, r);
    }

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值