旋转数组
给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
示例 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]
示例 2:
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]
提示:
- 1 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
- 0 <= k <= 10^5
解析图:
package LeetCode.初级算法.数组.旋转数组;
public class Main {
public static void main(String[] args) {
int[] nums = {1,2,3,4,5,6,7};
int k = 3;
for (int a:rotate(nums, k)) {
System.out.print(a+" ");
}
}
public static int[] rotate(int[] nums, int k) {
while (k != 0) {
nums=way(nums);
k--;
}
return nums;
}
public static int[] way(int[] num) {
/* nums_[0]=nums[nums.length-1];
nums_[1]=nums[2];
nums_[2]=nums[3];
...
num_[nums.length-1]=nums[1]*/
int[] num_ = new int[num.length];
int len = num.length - 1;
num_[0] = num[len];
for (int i = 1; i <= len; i++) {
num_[i] = num[i - 1];
}
return num_;
}
}