问题
#include <iostream>
using namespace std;
void rotateByOne(int arr[], int n)
{
int x = arr[0];
for (int y = 0; y < n - 1; y++)
{
arr[y] = arr[y + 1];
}
arr[n - 1] = x;
}
int main()
{
int n, d;
cin >> n >> d;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
while (d != 0)
{
rotateByOne(arr, n);
d--;
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
How Do i Reduce the compile time of this code which is written to take an array input of n integers and rotate array left by d times....... I found this on hacker rank and geeksforgeeks, Iam getting correct output from this code but the problem is time.
回答1:
If the goal is simply to write the rotated array, you don't need to modify the array or to create another one.
Note: using two loops instead of one allows to avoid the use of the modulo operation.
#include <iostream>
#include <vector>
int main() {
std::vector<int> arr = {0, 1, 2, 3, 4, 5, 6, 7};
int n = arr.size();
int d = 3;
for (int i = d; i < n; ++i) {
std::cout << arr[i] << " ";
}
for (int i = 0; i < d; ++i) {
std::cout << arr[i] << " ";
}
std::cout << "\n";
return 0;
}
回答2:
Learn to use ready algorithms and read documentation.
#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, d;
std::cin >> n >> d;
std::vector<int> v;
v.reserve(n);
std::copy_n(std::istream_iterator<int>{std::cin}, n, std::back_inserter(v));
std::rotate_copy(v.begin(), v.begin() + d, v.end(), std::ostream_iterator<int>{std::cout, " "});
return 0;
}
https://wandbox.org/permlink/mGciaeJqiH5PjGm1
来源:https://stackoverflow.com/questions/60340097/how-to-reduce-time-taken