本文主要是介绍LeetCode(67)-Rotate Array,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Rotate an array of n elements to the right by k steps.For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
思路:
- 题意:要求对给定长度的整形数组n进行平移,给定k,就平移3个位置(循环)
- 要求是在o(1)的空间,不能考虑数组的复制了,根据算法,这个平移转化为逆序。reverse(nums,0,n-k-1),reverse(nums,n-k,n-1),reverse(nums,0,n-1)等价,写一个reverse的函数。
代码:
public class Solution {public void reverse(int[] nums,int start,int end){while(start < end){int tmp = nums[start];nums[start] = nums[end];nums[end] = tmp;start++;end--;}}public void rotate(int[] nums, int k) {if(nums.length == 0){return;} int n = nums.length;k = k%n;reverse(nums,0,n-k-1);reverse(nums,n-k,n-1);reverse(nums,0,n-1);}
}
这篇关于LeetCode(67)-Rotate Array的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!