189. Rotate Array

小鱼儿 2022-06-03 05:17 291阅读 0赞
  1. Rotate an array of n elements to the right by k steps.
  2. 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].
  3. Note:
  4. Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

看到这道题就想到了以前做字符串旋转是一样的方法,其中比较好的解就是三步反转,这样能比使用将一个一个元素移动的时间复杂度低很多,若是使用上述一个一个移动,那么对于长度为n的数组,假设需要移动m个元素,那么总共需要m*n次操作,同时还需要设立一个变量来保存第一个元素,那么时间复杂度为O(mn),空间复杂度为O(1)。

实现代码:

  1. public class RotateArray {
  2. public void rotate(int[] nums, int k) {
  3. int m = nums.length;
  4. k %= m;
  5. reverserString(nums, 0, m-k-1);
  6. reverserString(nums, m-k, m-1);
  7. reverserString(nums, 0, m-1);
  8. }
  9. public void reverserString(int[] nums, int n, int m){
  10. while(n < m){
  11. int num = nums[n];
  12. nums[n++] = nums[m];
  13. nums[m--] = num;
  14. }
  15. }
  16. public static void main(String[] args){
  17. int[] nums = {
  18. 1,2,3,4,5,6,7};
  19. new RotateArray().rotate(nums,3);
  20. for (int num : nums) {
  21. System.out.println("num = " + num);
  22. }
  23. }

上面三次反转的过程:

这里写图片描述


这种方法的时间复杂度为O(n),空间复杂度为O(1),虽然这道题比较基础,但是却能体现了对数组结构的一个理解

发表评论

表情:
评论列表 (有 0 条评论,291人围观)

还没有评论,来说两句吧...

相关阅读