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?
题意:
轮换数组,将尾部数字轮换到首部
思路:
用Linkedlist 循环每次取尾部数字加入到首部
知识点:
- void不返回
- LinkedList是双向链表,
getLast()
addFirst(element)
添加到首部add(element)
顺序添加removeLast()
get(index)
LinkedList<Integer> A = new LinkedList<Integer>();
初始化
bug:
看到void以为要打印输出,但是这个结果是stdout,与answer不同。应该用nums数组存储结果,不用打印
class Solution {
public void rotate(int[] nums, int k) {
LinkedList<Integer> A = new LinkedList<Integer>();//初始化
int len = nums.length;
for(int i=0;i<nums.length;i++){
A.add(nums[i]);//nums转换成LinkedList
}
for(int i=0;i<k;i++){
int b = A.getLast();//获取尾部元素
A.addFirst(b);//将元素添加到首部
A.removeLast();//删除尾部元素
}
for(int i=0;i<len;i++){
nums[i] = A.get(i);//将LinkedList转换为数组
}
}
}