What's wrong with my code? Thanks!


  • 0
    T
    class Solution {
    public:
        void rotate(int nums[], int n, int k) {
            k = k%n;
            int a[k], i;
            for (i = 0; i < k; i++) {
                a[i] = nums[n-k-i];
            }
            for (i = n-k-1; i >= 0; i--) {
                nums[k+i] = nums[i];
            }
            for (i = 0; i < k; i++) {
                nums[i] = a[i];
            }
        }
    };
    

    it says "runtime error"
    and my another solution also says runtime error

    class Solution {
    public:
        void rotate(int nums[], int n, int k) {
            int *a,*b;
            k = k%n;
            a = nums; b = nums-k;
            reverse(a, n-k);
            reverse(b, k);
            reverse(nums, n);
        }
        void reverse(int *nums, int n) {
            int swap;
            for (int i = 0; i < n; i++) {
                swap = nums[i];
                nums[i] = nums[n-1-i];
                nums[n-1-i] = swap;
            }
        }
    };
    

    Thanks for helping!


  • 0
    L

    it's my AC code,maybe help you.

    void rot(int nums[],int s,int e)
    {
    int i = s,j = e-1,temp;
    while (i<j)
    {
    temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
    i++;
    j--;
    }
    }
    void rotate(int nums[], int n, int k) {
    if (k != 0 && n!=k)
    {
    rot(nums,0,n-k%n);
    rot(nums,n-k%n,n);
    rot(nums,0,n);
    }
    }


  • 0
    R

    In your second solution, you can add
    "if(k==0) return ;"
    after
    "k=k%n"


  • 0
    T

    thanks for replying


  • 0
    T

    thanks.
    I found that the real problem is the for loop in function reverse; after I changed
    for (int i = 0; i < n; i++) to for (int i = 0; i < n/2; i++)
    it accepted. Your suggestion is good though.


Log in to reply
 

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