Rotate Array
Description
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]
Tags: Array
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?
解讀題意
給定一個數組,一個k,求數組向右前進k後(超過數組長度,末項變爲首項),數組變成了什麼?
思路1
這是一個數組反轉的問題。假設k=3,有一個[1,2,3,4,5,6,7]數組,那麼可以這麼求解:
1. 7 6 5 4 3 2 1(反轉全部數)
2. 5 6 7 4 3 2 1(反轉前k個數)
3. 5 6 7 1 2 3 4(反轉n-k個數)
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
// 數組順序全部反過來
reverse(nums, 0, nums.length - 1);
// 反轉前k個
reverse(nums, 0, k - 1);
// 反轉n-k個
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
int temp = 0;
while (start < end) {
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
leetCode彙總:https://blog.csdn.net/qingtian_1993/article/details/80588941
項目源碼,歡迎star:https://github.com/mcrwayfun/java-leet-code