lintcode 80. Median

lintcode 80. Median_第1张图片
image.png

注意 quikselect 模板

算法导论
这是以right作为pivoit的情况;

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: An integer denotes the middle number of the array
     */
    int partition(vector &a, int left, int right){
        int pivoit  = a[right];
        int i = left - 1;
        for(int j= left; j <= right-1; j++){
            if(a[j] <= pivoit){
                i++;
                swap(a[i], a[j]);
            }
        }
        swap(a[i+1], a[right]);
        return i+1;
    }
    int median(vector &nums) {
        // write your code here
        int left = 0;
        int right = nums.size() - 1;
        int median = (nums.size()-1)>>1;
        //cout<

以left为pivoit的情况:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: An integer denotes the middle number of the array
     */
    int partition(vector &a, int left, int right){
        int pivoit  = a[left];
        int i = left;
        for(int j= left+1; j <= right; j++){
            if(a[j] <= pivoit){
                i++;
                swap(a[i], a[j]);
            }
        }
        swap(a[i], a[left]);
        return i;
    }
    int median(vector &nums) {
        // write your code here
        int left = 0;
        int right = nums.size() - 1;
        int median = (nums.size()-1)>>1;
        //cout<

你可能感兴趣的:(lintcode 80. Median)