Rotate an array of n elements to the right by k 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? Related problem: Reverse Words in a String II
Credits: Special thanks to @Freezen for adding this problem and creating all test cases.
我想到的就是反转,但是开始写的反转用了惯性思维,用下标控制,很不理想,花费大量时间还弄不精确,后来看了个湄公河,嘿嘿,一下反应到用m,n分别是起始位置和结束位置,然后一直到m
public void rotate(int[] nums, int k) { k = k % nums.length; if (k >= 1 && nums.length > k) { reverseArr1(nums, 0, nums.length - 1); reverseArr1(nums, 0, k - 1); reverseArr1(nums, k, nums.length - 1); } } /** * * @param nums * @param m * 要交换的起始位置,按照数组下标0开始 * @param n * 要交换的结束位置,按照数组下标0开始 */ public void reverseArr1(int[] nums, int m, int n) { int temp = 0; while (m < n) { temp = nums[m]; nums[m] = nums[n]; nums[n] = temp; m++; n--; } }这也应该算是最佳解了。给大家看看最开始写的逆转算法。蠢死了
/** * @param nums * @param m * 起始位置1开始 * @param n * 结束位置 */ public void reverseArr(int[] nums, int m, int n) { int temp = 0, len = n - 1; for (int i = m - 1; i < ((n - m) / 2 + m); i++) { temp = nums[i]; nums[i] = nums[len - i]; nums[len - i] = temp; } }还有四个解法,明天早上更新吧。
给个链接LeetCode官方谈论区
