My solution by C++. Any way to improve the performance and buffer space?


  • -1
    X

    class Solution {
    public:
    void rotate(int nums[], int n, int k) {
    int tmp[n];

        if (k > n)
            k %= n;
        for (int i=0;i<n; i++)
            if (i<k) {
                tmp[i]=nums[n-k+i];
            } else {
                tmp[i]=nums[i-k];
            }
        for (int j=0; j<n;j++) nums[j]=tmp[j];
    }
    

    };


  • 0
    A
     change if..else to:
    
       for(i=0; i<n; i++) {
        tmp[(i+k)%n] = nums[i];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.