【发布时间】:2019-07-18 12:58:45
【问题描述】:
我得到了一个 n 元素数组和一个整数 K。我必须以相反的顺序打印K 元素的子数组。
我将元素存储在向量中并增加计数。一旦计数等于K,以相反的顺序打印向量并清除向量的所有元素。
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t; // No of test cases
cin >> t;
while (t--)
{
// Size of array and The size of each group
int n, k;
cin >> n >> k;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
vector <int> my_nums;
int count = 0;
for (int i = 0; i < n; i++)
{
my_nums.push_back(arr[i]);
count++;
if (count == k)
{
for (auto it = my_nums.rbegin(); it != my_nums.rend(); ++it)
{
cout << *it << " ";
}
//Clear all elements in vector
my_nums.clear();
}
}
cout << endl;
}
return 0;
}
ex:
I/P:
1
8 3
1 2 3 4 5 6 7 8
Expected O/P:
3 2 1 6 5 4 8 7
Actual O/P:
3 2 1
【问题讨论】:
-
请注意
int arr[n];是一个可变长度数组 (VLA),不是标准 C++。您可以直接将其替换为std::vector<int> arr(n);之类的向量,以获得可移植代码。
标签: c++ algorithm c++11 reverse stdvector