leetcode 189. Rotate Array旋转数组
2017-10-17 10:56
483 查看
题目描述:
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].
解题思路:
数组向右进行旋转,每旋转n次恢复原状,所以k要mod n得到简化后的旋转次数。最先想到的是新建一个整型数组,分两部分进行,存储旋转后的数组,最后修改原数组nums中的顺序。
代码:
改进:
由于新建了一个数组,造成了内存空间的占用,想办法仅仅利用数组nums进行旋转。基本的想法是:例如数组为 nums = [1,2,3,4,5,6,7] 且 k = 3。首先,我们翻转[1,2,3,4],变为[4,3,2,1];然后我们翻转[5,6,7],变为[7,6,5];最后我们翻转整个数组,[4,3,2,1,7,6,5] —> [5,6,7,1,2,3,4].
代码:
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].
解题思路:
数组向右进行旋转,每旋转n次恢复原状,所以k要mod n得到简化后的旋转次数。最先想到的是新建一个整型数组,分两部分进行,存储旋转后的数组,最后修改原数组nums中的顺序。
代码:
class Solution { public void rotate(int[] nums, int k) { int n = nums.length; int[] result = new int ; int num = k % n; for (int i = n - num, j = 0; i < n && j<n; i++,j++){ result[j] = nums[i]; } for (int i = 0,j = num; i<n && j<n;i++,j++){ result[j] = nums[i]; } for(int i = 0;i<n;i++){ nums[i] = result[i]; } } }
改进:
由于新建了一个数组,造成了内存空间的占用,想办法仅仅利用数组nums进行旋转。基本的想法是:例如数组为 nums = [1,2,3,4,5,6,7] 且 k = 3。首先,我们翻转[1,2,3,4],变为[4,3,2,1];然后我们翻转[5,6,7],变为[7,6,5];最后我们翻转整个数组,[4,3,2,1,7,6,5] —> [5,6,7,1,2,3,4].
代码:
class Solution { public void rotate(int[] nums, int k) { if(nums == null || nums.length <2){ return; } int num = k % nums.length; reverse(nums,0,nums.length-1-num); reverse(nums,nums.length-num,nums.length-1); reverse(nums,0,nums.length-1); } public void reverse(int[] nums, int i,int j){ while(i<j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; i++; j--; } } }
相关文章推荐
- 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(旋转数组)
- 面试_java:数组:旋转数组:rotate array(189)
- leetcode解题之189 # Rotate Array Java版 (对数组的部分翻转)
- 189. Rotate Array (旋转数组)
- LeetCode-189:Rotate Array (数组的循环移位)
- 189. Rotate Array 旋转数组
- leetcode Rotate Array 旋转数组
- Rotate Array 数组旋转 leetcode
- LeetCode Rotate Array(数组的旋转)
- 1.1数组和链表:189. Rotate Array(Leetcode)
- leetcode:Rotate Array旋转数组
- [LeetCode]12. Rotate Array旋转数组