leetcode解题之189 # Rotate Array Java版 (对数组的部分翻转)
2017-03-14 15:45
537 查看
189. Rotate Array
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?
题目大意
给定一个n个长度的数组,将它向右旋转k个位置。
解题思路
先将k转换成[0, n-1]内的数。再对整个数组进行翻转,再对[0, k-1]位置的数字进行反转,再对剩下的部分进行翻转。
注意保持k为正
public void rotate(int[] nums, int k) { int len = nums.length; // 保证k为正 k = (len + (k % len)) % len; // 对整个数组翻转 rotateCore(nums, 0, len - 1); // 对下标0~k-1的数组翻转 rotateCore(nums, 0, k - 1); // 对下标k~len-1的数组翻转 rotateCore(nums, k, len - 1); } /** * @param nums * 翻转数组(下标为前闭后闭) * @param start * 翻转数组的开始下标 * @param end * 翻转数组的结束下标 */ 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]; } }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【189-Rotate Array(旋转数组)】
- Leetcode:189. Rotate Array(JAVA)
- leetcode_189. Rotate Array 原地旋转数组
- 1.1数组和链表:189. Rotate Array(Leetcode)
- LeetCode-189:Rotate Array (数组的循环移位)
- 面试_java:数组:旋转数组:rotate array(189)
- 【LeetCode】189.Rotate Array(Easy)解题报告
- leetcode-189 Rotate Array 旋转数组
- LeetCode Rotate Array 翻转数组
- LeetCode 189. Rotate Array (旋转数组)
- [leetcode] 189. Rotate Array 解题报告
- leetCode 189. Rotate Array 数组
- [Leetcode] 189. Rotate Array 解题报告
- LeetCode 189. Rotate Array(旋转数组)
- [LeetCode] 189. Rotate Array 旋转数组
- 【LeetCode】189. Rotate Array 解题报告
- leetcode 189. Rotate Array旋转数组
- leetcode 189. Rotate Array-旋转数组
- Java [Leetcode 189]Rotate Array
- LeetCode(189) Rotate Array(Java)