【发布时间】:2022-07-18 00:43:36
【问题描述】:
我实际上是在尝试解决 K 旋转问题,我们必须将元素的键数向右旋转并将它们放在左侧。 我已经使用普通数组而不是向量检查了整个代码,它工作正常,但是当我运行它时,带有向量数组的函数从不返回任何内容。 我检查了所有在线资源,但由于逻辑和语法都是正确的,因此无法确定究竟是什么错误。 请帮忙解决这个问题!
#include<bits/stdc++.h>
using namespace std;
vector<int> rotate_array(vector<int> arr, int n, int key)
{
int i,j=0;
vector<int> subst;
for(i=n-1; i>=n-key; i--)
{
subst[j] = arr[i];
j++;
}
j=0;
for(i=key; i<n; i++)
{
subst[i] = arr[j];
j++;
}
return subst;
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
// output for this should be -- {4, 5, 1, 2, 3}
int n = arr.size();
int key = 2;
vector<int> array = rotate_array(arr, n, key);
for(int i=0; i<n; i++)
{
cout<<array[i]<<" ";
}
}
【问题讨论】: