189. Rotate Array
Rotate an array of n elements to the right byk steps.
For example, with n = 7 and k = 3, the array
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]Hint:
Could you do it in-place with O(1) extra space?
given an array of n lengths, rotate it to the right by k positions.first convert k into the number in [0, n-1]. Flip the entire array, flip the number at the [0, K-1] position, and flip the rest.
note that k is positive
Rotate an array of n elements to the right byk steps.
For example, with n = 7 and k = 3, the array
[1,2,3,4,5,6,7]
is rotated to[5,6,7,1,2,3,4]
.Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]Hint:
Could you do it in-place with O(1) extra space?
given an array of n lengths, rotate it to the right by k positions.first convert k into the number in [0, n-1]. Flip the entire array, flip the number at the [0, K-1] position, and flip the rest.
note that k is positive
public void rotate(int[] nums, int k) {
int len = nums.length;
// Ensure that k is positive
k = (len + (k % len)) % len;
// Flip the entire array.
rotateCore(nums, 0, len - 1);
// Flip the array of subscript 0~k-1.
rotateCore(nums, 0, k - 1);
// Flip the array of subscript k~len-1.
rotateCore(nums, k, len - 1);
}
/**
* @param nums
* Flip the array (the subscript is closed front to back).
* @param start
* Subscript to the beginning of the flipped array
* @param end
* End subscript for flipping arrays
*/
private void rotateCore(int[] nums, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
}
Read More:
- Leetcode 34 finds the first and last position of an element in the sorted array (medium)
- matlab Error Subscript indices must either be real positive integers or logicals.
- Two dimensional array and pointer to one dimensional array
- Proxy error:could not proxy request
- How to Use the object of ES6 to clear the object value
- The usage of Matlab function downsample
- Array initializer is not allowed here
- C++ foundation — clear/erase/pop of string class_back
- Error creating bean with name ‘xxcontroller’
- (Windows+xrdp+ubuntu16.04) Remote server error: “password failed error-problem connecting”
- array type has an incomplete element type
- Principle and usage of feof ()
- An example of drawing rotating cube with OpenGL
- HTTP 400 error – bad request
- Java foundation — printing Yang Hui triangle
- Error: request failed with status code 500
- There will be row spacing problems in algorithm use in latex. Please use the ‘setstretch {1.35}
- In Java, int is converted to string, and zero is added before the number of bits is insufficient
- Lua — using remove to delete table data
- Python error: typeerror: ‘Int’ object is not subscribable