public class Solution {
public void rotate(int[] nums, int k) {
if (nums == null  nums.length == 0) {
return;
}
k = k % nums.length;
reverse(nums, 0, nums.lengthk1);
reverse(nums, nums.lengthk, nums.length1);
reverse(nums, 0, nums.length1);
}
private void reverse(int[] num, int left, int right) {
while (left < right) {
int t = num[left];
num[left] = num[right];
num[right] = t;
left++;
right;
}
}
}
Java solution with O(1) space


check this link: https://leetcode.com/discuss/27387/summaryofcsolutions
 Reverse the first n  k elements, the last k elements, and then all the n elements.
Time complexity: O(n). Space complexity: O(1).
class Solution { public: void rotate(int nums[], int n, int k) { k = k%n; // Reverse the first n  k numbers. // Index i (0 <= i < n  k) becomes n  k  i. reverse(nums, nums + n  k); // Reverse tha last k numbers. // Index n  k + i (0 <= i < k) becomes n  i. reverse(nums + n  k, nums + n); // Reverse all the numbers. // Index i (0 <= i < n  k) becomes n  (n  k  i) = i + k. // Index n  k + i (0 <= i < k) becomes n  (n  i) = i. reverse(nums, nums + n); } };

Hi, shanxin136. Great explanations using changes of indexes :) But I think you may have made some offby1 errors, the first should be
i
ton  k  1  i
, the second should ben  k  i
ton  1  i
, and the last reverse should bei
ton  1  i
, which gives the same result as yours.