整数无序数组求第K大数(暴力|快排) - 滴滴出行2018校园招聘内推笔试-研发工程师

时间限制:1S
空间限制:32768K

题目描述:
给定无序整数序列,求第K大的数,例如{45,67,33,21},第2大的数为45

输入描述:
输入第一行为整数序列,数字用空格分割,如:45 67 33 21
输入第二行为一个整数K,K在数组长度范围内,如:2

输出描述:
输出第K大的数,本例为第2大的数:45

示例:
输入
45 67 33 21
2

输出
45

思路:本题数据小直接暴力,求类似的题目可以用快排思想,代码中注释部分为排序求解

#include <iostream>
using namespace std;
const int Maxn = 1005;

void swap(int a[Maxn], int l, int r)
{
    int temp = a[l];
    a[l] = a[r];
    a[r] = temp;
}

int quickSort(int a[Maxn], int k, int l, int r)
{
    if(l==r)
        return a[l];
    int key = a[l];
    int left = l, right = r;
    while(left<right)
    {
        while(a[right]<key && left<right)
            right--;
        if(left<right)
            swap(a, left, right);
        while(a[left]>=key && left<right)
            left++;
        if(left<right)
            swap(a, left, right);
    }
    a[left] = key;
    if(left==k)
        return a[left];
    else if(left>k)
        return quickSort(a, k, l, left-1);
    else
        return quickSort(a, k, left+1, r);
}

int main()
{
    int a[Maxn], k;
    int count = 0;
    while(cin >> a[count++]);
    cout << quickSort(a, a[count-2]-1, 0, count-3) << endl;
    return 0;
}
/*
45 67 33 21
2
*/

//#include <iostream>
//#include <algorithm>
//using namespace std;
//const int Maxn = 1005;
//
//int cmp(const int& a, const int& b)
//{
//    return a>b;
//}
//
//int main()
//{
//    int a[Maxn], k;
//    int count = 0;
//    while(cin >> a[count++]);
//    sort(a, a+count-2, cmp);
//    cout << a[a[count-2]-1] << endl;
//    return 0;
//}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值