leetcode-189 Rotate Array 旋转数组



《编程之美》P221

Rotate an array ofn elements to the right byk steps.

For example, withn = 7 andk = 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 differentways to solve this problem.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

Related problem:Reverse Words in a String II

Credits:
Special thanks to
@Freezen for addingthis problem and creating all test cases.

解法一:将后k位翻转,再将前n-k位翻转,最后翻转整个数组,即得到结果


public class Solution {
    public void rotate(int[] nums, int k) {
        //先判断输入参数是否合法
        if((nums != null) && (nums.length > 0) && (k > 0))
        {
            k %= nums.length;
            if(k != 0)
            {
                //颠倒后k个数字
                reverse(nums,nums.length - k,nums.length - 1);
                //颠倒前n-k个数字
                reverse(nums,0,nums.length - k - 1);
                //颠倒整个数组
                reverse(nums,0,nums.length - 1);
            }
        }
    }
    
    //颠倒一个数组中的所有元素
    private void reverse(int[] nums,int start,int end)
    {
        for(int i = start ; i * 2 <= (start+end); i++)
        {
            int temp = nums[i];
            nums[i] = nums[start+end-i];
            nums[start+end-i] = temp;
        }
    }
}

解法二:将后面k个数分别按倒序移动至头部


  [1,2,3,4,5,6,7]


k=1: [7,1,2,3,4,5,6]


k=2: [6,7,1,2,3,4,5]


k=3: [5,6,7,1,2,3,4]


明显时间复杂度性能较差

public class Solution {
    public void rotate(int[] nums, int k) {
        //先判断输入参数是否合法
        if((nums != null) && (nums.length > 0) && (k > 0))
        {
            k %= nums.length;
            while(k != 0)
            {
                reverse_head(nums);
            }
        }
    }
    
    //将数组最后一个数字移至头部
    private void reverse_head(int[] nums)
    {
        int tail = nums[nums.length - 1];
        for(int j = nums.length - 1;j > 0; j --)
        {
            nums[j] = nums[j - 1];
        }
        nums[0] = tail;
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值