LeetCode Top Interview Questions 189. Rotate Array (Java版; Easy)
题目描述
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?
第一次做; 环状替代法; 不如力扣题解写得简洁; 移动过程有点类似链表反转操作
classSolution{publicvoidrotate(int[] nums,int k){if(nums==null || nums.length==0)return;int n = nums.length;//小优化
k = k%n;//处理过的元素的个数; 一共需要处理n个元素int count =0;//待处理的位置int start =0;for(; count<n; start++){//待处理的位置int i = start;//待处理的元素int cur = nums[i];//下面的操作流程有点类似链表翻转int index;int next;do{//save next//cur移动到index位置
index =(i + k)% n;//移动元素之前先保存下一个位置的元素
next = nums[index];//execute//移动
nums[index]= cur;//update//处理过的元素个数++
count++;
i = index;
cur = next;}while(i!=start);}}}
LeetCode Top Interview Questions 189. Rotate Array (Java版; Easy)
welcome to my blogLeetCode Top Interview Questions 189. Rotate Array (Java版; Easy)题目描述Given an array, rotate the array to the right by k steps, where k is non-negative.Example 1:Input: [1,2,3,4...