LeetCode 189. Rotate Array (旋转数组)
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
题目标签:Array
题目给了我们一个数组 和 k。 让我们 旋转数组 k 次。
这里有一个很巧妙的方法:
利用数组的length - k 把数组 分为两半;
reverse 左边和右边的数组;
reverse 总数组。
举一个例子:
1 2 3 4 5 6 7 如果k = 3 的话, 会变成 5 6 7 1 2 3 4
1 2 3 4 5 6 7 middle = 7 - 3 = 4,分为左边 4个数字,右边 3个数字
4 3 2 1 7 6 5 分别把左右reverse 一下
5 6 7 1 2 3 4 把总数组reverse 一下就会得到答案
Java Solution:
Runtime beats 15.37%
完成日期:04/13/2017
关键词:Array
关键点:利用k把数组分两半;reverse左右两边数组;reverse总数组
public class Solution { public void rotate(int[] nums, int k) { if(nums == null || nums.length == 0 || k % nums.length == 0) return; int turns = k % nums.length; int middle = nums.length - turns; reverse(nums, 0, middle-1); // reverse left part reverse(nums, middle, nums.length-1); // reverse right part reverse(nums, 0, nums.length-1); // reverse whole part } public void reverse(int[] arr, int s, int e) { while(s < e) { int temp = arr[s]; arr[s] = arr[e]; arr[e] = temp; s++; e--; } } }
参考资料:
http://www.cnblogs.com/grandyang/p/4298711.html
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
- LeetCode 189 Rotate Array(旋转数组)
- leetcode 189. Rotate Array-旋转数组
- [LeetCode] 189. Rotate Array 旋转数组
- 【LeetCode-面试算法经典-Java实现】【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]12. Rotate Array旋转数组
- LeetCode Rotate Array 旋转数组
- 面试_java:数组:旋转数组:rotate array(189)
- 189. Rotate Array (旋转数组)
- LeetCode-189:Rotate Array (数组的循环移位)
- leetcode Rotate Array 旋转数组
- LeetCode Rotate Array(数组的旋转)
- leetcode:Rotate Array旋转数组
- 189. Rotate Array 旋转数组
- 1.1数组和链表:189. Rotate Array(Leetcode)