leetcode 189. Rotate Array

今日份leetcode 189. Rotate Array
Description:
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?

我的思路是先用一个list存放旋转处理好的数字,然后在转给数组。因为list.add(0,object o)方法指定了添加位置为首位,这样后面的list.add(0,object o)可以源源不断的放在首位,前面添加的则自动后移。这样正好符合题目中旋转后的规则。
题目中的example都是k<nums.length的情况,千万不要只考虑这种情况,还有k>nums.length的情况。当k是nums.length的倍数时,则数组不会改变。

class Solution {
    public void rotate(int[] nums, int k) {
        List<Integer> list = new ArrayList<Integer>();
        Integer[] numsInteger = new Integer[nums.length];//与list<Integer>类型一致
        int pointRight = nums.length-1;//要旋转的元素的索引
        int pointLeft = 0;  //剩下不需旋转的元素的索引
        if(k>nums.length)
            k=k%nums.length;
        if(k<=nums.length){     
        for(int i=0;i<k;i++){
           list.add(0,nums[pointRight]);
            pointRight--;
        }
        for(int i=k;i<nums.length;i++){
            list.add(i,nums[pointLeft]);
            pointLeft++;
        }
        list.toArray(numsInteger);
        for(int i=0;i<nums.length;i++){  //再转回来....
            nums[i]=numsInteger[i];
        }
        }
    }
}

这样写耗时大约15ms,还是太复杂。
下面是一种更好的写法:

class Solution {
   public void rotate(int[] nums, int k) {
    k %= nums.length;
    reverse(nums, 0, nums.length - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, nums.length - 1);
}

public void reverse(int[] nums, int start, int end) {
    while (start < end) {
        int temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;
        start++;
        end--;
    }
}
}

这种方法更为巧妙,根据题目转换后数组的特征,可先将原始数组倒置,然后分别倒置本应旋转的部分和不需旋转的部分。耗时大约1ms。

关于空间复杂度的一些问题发现自己有些遗忘要补充一下,但实在太饿了,先放放…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值