LeetCode - Rotate Array
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - Rotate Array相关的知识,希望对你有一定的参考价值。
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input:[1,2,3,4,5,6,7]
and k = 3 Output:[5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right:[7,1,2,3,4,5,6]
rotate 2 steps to the right:[6,7,1,2,3,4,5]
rotate 3 steps to the right:[5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Solution 1 - Intermediate Array
Space is O(n) and time is O(n).
class Solution { public void rotate(int[] nums, int k) { if(nums == null){ return; } if(k >= nums.length){ k = k % nums.length; } int[] temp = new int[nums.length]; int count=0; for(int i=nums.length-k; i<nums.length; i++){ temp[count]=nums[i]; count++; } for(int i=0; i<nums.length-k; i++){ temp[count] = nums[i]; count++; } System.arraycopy(temp, 0, nums, 0, nums.length); } }
Solution 2 - Bubble Rotate
O(1) space,O(n*k) time
class Solution { public void rotate(int[] nums, int k) { if(nums == null){ return; } if(k >= nums.length){ k = k % nums.length; } for (int i=0; i<k; i++){ for(int j = nums.length-1; j > 0; j--){ int temp = nums[j-1]; nums[j-1] = nums[j]; nums[j] = temp; } } } }
Solution 3 - Reversal
Can we do this in O(1) space and in O(n) time? The following solution does.
Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:
1. Divide the array two parts: 1,2,3,4 and 5, 6 2. Reverse first part: 4,3,2,1,5,6 3. Reverse second part: 4,3,2,1,6,5 4. Reverse the whole array: 5,6,1,2,3,4
class Solution { public void rotate(int[] nums, int k) { if(nums == null){ return; } if(k >= nums.length){ k = k % nums.length; } reverse(nums, 0, nums.length-k-1); reverse(nums, nums.length-k, nums.length-1); reverse(nums, 0, nums.length-1); } public void reverse(int[] nums, int left, int right){ if(nums == null || nums.length == 1){ return; } while(left < right){ int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } } }
以上是关于LeetCode - Rotate Array的主要内容,如果未能解决你的问题,请参考以下文章