189. 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].

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

  1. swap函数都忘了,也是醉了
  2. k步可能很大,所以需要%=数组长度

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

从左往右的:

[一刷]:

  1. swap函数需要带入index的,所以内部i j 需要初始化

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

reverse都是用swap函数,套路都一样

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

swap

public void swap (int[] nums, int i, int j) {
        while (i < j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            
            i++;
            j--;
        }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

swap的所有题

 [代码风格] :

class Solution {
    public void rotate(int[] nums, int k) {
        //cc
        if (nums == null || nums.length == 0) {
            return ;
        }
        
        //ini, k
        k %= nums.length;
        
        //swap
        swap(nums, 0, nums.length - k - 1);
        swap(nums, nums.length - k, nums.length - 1);
        swap(nums, 0, nums.length - 1);
        //return
    }
    
    public void swap (int[] nums, int i, int j) {
        while (i < j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            
            i++;
            j--;
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8872598.html