LeetCode-探索-初级算法-数组-3. 旋转数组(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-数组-3. 旋转数组(个人做题记录,不是习题讲解)

  • 语言:java

  • 执行时间:0ms

  • 个人思路:没整出来。

  • 参考代码:

    class Solution {
        public void rotate(int[] nums, int k) {
            int len = nums.length-1;
            k = k%nums.length;
            rev(nums,0,len);
            rev(nums,0,k-1);
            rev(nums,k,len);
        }
    
        public void rev(int[] nums,int start,int end){
            while(start<end){
                int temp = nums[start];
                nums[start++] = nums[end];
                nums[end--] = temp;
            }
        }
    }
    
  • 个人代码(1ms):

    class Solution {
        public void rotate(int[] nums, int k) {
            int len = nums.length;
            k = k % len;
            if(k>0){
                rev(nums,0,len-1);
                rev(nums,0,k-1);
                rev(nums,k,len-1);
            }
        }
        public void rev(int[] nums,int start,int end){
            while(start<end){
                int tmp = nums[start];
                nums[start++] = nums[end];
                nums[end--] = tmp;
            }
        }
    }
    

你可能感兴趣的:(非讲解,LeetCode,原创)