Description
找到给定数组的给定区间内的第K小的数值。
Input
输入第一行为用例个数, 每个测试用例输入的第一行为数组,每一个数用空格隔开;第二行是区间(第几个数到第几个数,两头均包含),两个值用空格隔开;第三行为K值。
Output
结果。
Sample Input 1
1
1 2 3 4 5 6 7
3 5
2
Sample Output 1
4
思路
暴力
#include <iostream>
#include <vector>
#include <string.h>
#include <string>
#include <deque>
#include <sstream>
using namespace std;
int main()
{
int t;
cin >> t;
for (int turn = 0; turn < t; turn++) {
int res = 0, len;
//将一组未知个数的数字读入一个动态数组数组vector a
stringstream ss;
string str;
int sin;
cin.ignore();
getline(cin, str);
vector<int> a;
ss << str;
while (ss >> sin) {
a.push_back(sin);
}
int alen = a.size();
cin >> len;
//题目变为对数组a中aLen个数字进行滑动查找
int sum = 0;
if (len < 1 || alen < len || alen<1) {
if (turn + 1 == t) {
printf("%d", res);
}
else {
printf("%d\n", res);
}
}
else {
int maxNum = 0;
for (int i = len - 1; i < alen; i++) {
maxNum = a[i];
for (int j = i - 1; j > i - len; j--) {
if (maxNum < a[j]) {
maxNum = a[j];
}
}
sum += maxNum;
}
res = sum;
if (turn + 1 == t) {
printf("%d", res);
}
else {
printf("%d\n", res);
}
}
}
return 0;
}