rotate array
Question Description: Given an array, move the elements of the array k positions to the right, where k is a non-negative number.
Advanced:
- Come up with as many solutions as possible, there are at least three different ways to approach this problem.
- Can you solve this problem using an in-place algorithm with O(1) space complexity?
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/rotate-array/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Array Traversal
First of all, you can know that the number where the index bit i of the array is located should be placed in
(i + k) % N
, where N is the size of the array, so by traversing the array and declaring a spare array to put the rotated array, The specific process is as follows:
- First move each bit of the array to the position that should be rotated;
- Then reset the nums array.
public class LeetCode_189 {
/**
* 备用空间
*
* @param nums
* @param k
*/
public static void rotate(int[] nums, int k) {
int[] copy = new int[nums.length];
// 首先将数组的每一位移到应该轮转到的位置
for (int i = 0; i < nums.length; i++) {
copy[(i + k) % nums.length] = nums[i];
}
// 然后重置nums数组
for (int i = 0; i < nums.length; i++) {
nums[i] = copy[i];
}
}
public static void main(String[] args) {
// 测试用例
int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7};
System.out.println("轮转之前:");
for (int num : nums) {
System.out.print(num + " ");
}
System.out.println();
System.out.println("轮转之后:");
rotate(nums, 3);
for (int num : nums) {
System.out.print(num + " ");
}
}
}
[Daily Message] A wise man smiles, but a fool is cold; a wise man remembers other people's names, and a fool wishes his name to be remembered; a wise man understands other people's minds, and a fool expresses his own needs; a wise man is good at listening, but a fool is impatient; a wise man agrees first , the fool will deny first; the wise let others say "yes" gradually, and the fool will cause more controversy;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。