topic:
Given an array, the elements of the array to the right by k positions, wherein k is non-negative. Example 1 : Input: [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ], and = K 3 Output: [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ] Explanation: Rotate right 1 Step: [ 7 , 1 , 2 , 3 , 4 , 5 , 6 ] rotates clockwise 2 steps: [6 , 7 , 1 , 2 , 3 , 4 , 5 ] Rotate Right 3 steps: [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ] Example 2 : Input: [ - 1 - 100 , 3 , 99 ] = and K 2 output: [ 3 , 99 - 1 - 100 ] explanation: Rotate right 1Step: [ 99 - . 1 - 100 , 3 ] rotates clockwise 2 steps: [ 3 , 99 - . 1 - 100 ]
Array failing to issue decisions about the rotation
. 1 2 . 3 . 4 K = 2 integrally rotate . 4 . 3 2 . 1 before rotation 2 . 3 . 4 2 . 1 behind the rotation of the two . 3 . 4 . 1 2 achievements reached!
So the idea is very simple, first write a reverse algorithm
Then call three times a reverse algorithm on it
class Solution { public void rotate(int[] nums, int k) {
if (k> nums.length) {Do not forget the critical value judgment! ! ! ! ! ! !
% nums.length K = K;
}
transArray(nums,0,nums.length-1); transArray(nums,0,k-1); transArray(nums,k,nums.length-1); } public static void transArray(int[] nums, int start, int end){ int arr_length = end + 1 - start; int tmp = 0; for(int i=start;i<start+arr_length/2;i++){ tmp = nums[i]; nums[i] = nums[end-i+start]; nums[end-i+start] = tmp; } } }
Process derive the end-i + start there is some error.