# What's wrong with my code? Thanks!

• ``````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!

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

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

• thanks for replying

• 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.

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