# Three simple solutions using C++

• ``````void rotate(int nums[], int n, int k) {
while(k>0) {
int tmp = nums[n-1];
for(int i=n-1; i>0; i--) {
nums[i] = nums[i-1];
}
nums[0] = tmp;
k--;
}
}

void rotate(int nums[], int n, int k) {
if (k<=0) {
return;
}
int tmp = nums[n-1];
for(int i=n-1; i>0; i--) {
nums[i] = nums[i-1];
}
nums[0] = tmp;
rotate(nums, n, k-1);
}

void strReverse(int nums[], int bgn, int end) {
int lst = end-1;
while(bgn<lst) {
int tmp = nums[bgn];
nums[bgn] = nums[lst];
nums[lst] = tmp;
bgn++;
lst--;
}
}

void rotate(int nums[], int n, int k) {
if (k<=0) {
return;
}
k = k%n;
strReverse(nums, 0, n-k);
strReverse(nums, n-k, n);
strReverse(nums, 0, n);
}``````

• good work!
I do not know why my code runs well in codeblocks while always runtime error in oj??

``````class Solution
{
public:
void rotate(int nums[], int n, int k)
{
k = k % n;
if(k == 0 || n == 1) return;
int tem[n];
int j = 0;
for(int i = n - k; i < n; ++i,++j)
tem[j] = nums[i];
for(int i = 0; i <= k ; i++,j++)
tem[j] = nums[i];
for(int i = 0; i < n; ++i)
nums[i] = tem[i];
}

};``````

• Most of them do not work now. I've ported the solution from this answer

``````class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
l = len(nums)

k %= l
if k == 0:
return

g = l - k;
self.__reverse(nums, 0, g);
self.__reverse(nums, g, l);
self.__reverse(nums, 0, l);

def __reverse(self, nums, s, e):
e -= 1
while s < e:
nums[s], nums[e] = nums[e], nums[s]
s += 1
e -= 1``````

• @turbocv the first method is Time Limit Exceeded,can u explain this ? thank you.

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