【C++】线性时间选择

#include <iostream>
#include <vector>
using namespace std;

void swap(vector<int>& nums, int a, int b)
{
    int temp = nums[a];
    nums[a] = nums[b];
    nums[b] = temp;
}

int linear_select(vector<int>& nums, int begin, int end, int target)
{
    int i = begin;
    int j = end;
    int pivot = begin;

    while(i<j){
        while(i<j && nums[j]>=nums[pivot]){
            j--;
        }
        while(i<j && nums[i]<=nums[pivot]){
            i++;
        }
        swap(nums, i, j);
    }

    swap(nums, pivot, i);

    int order = i-begin+1;
    if(order==target){
        return nums[j];
    }
    else if(order < target){
        return linear_select(nums, j+1, end, target-order);
    }
    else{
        return linear_select(nums, begin, j-1, target);
    }
}


int main() {
    vector<int> array1 = {1,5,4,3,2,9,8,6,7,0};
    vector<int> array2 = {1,2,3,4,5,6,7,8,9,10};

    int ans1 = linear_select(array1, 0, array1.size()-1, 5);
    int ans2 = linear_select(array2, 0, array2.size()-1, 5);

    cout << ans1 << endl << ans2 << endl;

    return 0;
}

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值