您的位置:首页 > 编程语言 > Java开发

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];
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息