码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Median"

时间:2015-09-15 07:00:36      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

Partial Sort.

技术分享
class Solution {
public:
    /**
     * @param nums: A list of integers.
     * @return: An integer denotes the middle number of the array.
     */
    int partition(vector<int> &nums, int s, int e)
    {
        if (s > e) return -1;

        int pivot = nums[s];
        swap(nums[s], nums[e]);
        int i = s, j = s;
        while(j < e)
        {
            if(nums[j] <= pivot)
            {
                swap(nums[i ++], nums[j]);
            }
            j ++;
        }
        swap(nums[i], nums[e]);

        return i;   
    }
    int findKth(vector<int> &nums, int inx, int s, int e)
    {
        int pi = partition(nums, s, e);
        if(pi == inx) return nums[inx];
        if (pi < inx) return findKth(nums, inx, pi+1, e);
        return findKth(nums, inx, s, pi-1);
    }
    int median(vector<int> &nums) {
        size_t len = nums.size();
        int mid = len/2 - (len%2?0:1);
        return findKth(nums, mid, 0, len - 1);
    }
};
View Code

LintCode "Median"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4809044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!