如何减少时间 [英] how to reduce time taken

查看:72
本文介绍了如何减少时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

我如何减少此代码的编译时间n个整数的数组输入,并将数组旋转d次。……
我在黑客排名和geeksforgeeks上发现了这一点,Iam从此代码获取了正确的输出,但问题是时间。

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.

推荐答案

如果目标只是编写旋转的数组,则无需修改数组或创建另一个数组

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;
}

这篇关于如何减少时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆