189. Rotate array
Given an array, rotate the elements in the array k positions to the right, where k is a non-negative number.
Example 1:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]
Example 2:
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]
hint:
- 1 <= nums.length <= 105
- -231 <= nums[i] <= 231 - 1
- 0 <= k <= 105
Answer ideas:
- Because there is no return value here, it is inconvenient to directly operate on the original array, so first make a copy of the original array.
- Shift all elements by k positions
- Just put the original element of arr[i] at the position of arr[(i+k)%arr.length]
class Solution {
public void rotate(int[] nums, int k) {
int []arr=new int[nums.length];//创建同等大小的新数组
for(int i=0;i<nums.length;i++){
arr[i]=nums[i]; //将原数组复制到新数组中,因为这里没有返回值,直接在原数组中操作不方便
}
int n=nums.length; //记录数组长度
for(int i=0;i<arr.length;i++){
nums[(i+k)%n]=arr[i];//向右移动三个位置,第一个变成了第四个,以此类推,位移后的位置为当前位置+k,再对 数组长度取余
}
}
}