LeetCode 189. Rotate Array

题目:

给定一个数组,将该数组向右旋转k步,其中k是非负的。

Given an array, rotate the array to the right by k steps, where k is non-negative.

Input: [1,2,3,4,5,6,7]   and k = 3      Output: [5,6,7,1,2,3,4]
Input: [-1,-100,3,99]    and k = 2      Output: [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?

方法:

根据k将数组分为两个部分,分别是0~k-1和k~len-1,先分别将两个部分的数组颠倒,再将整个数组颠倒,可得到所要求的数组

同【剑指offer第二版——面试题58(java)】——https://blog.csdn.net/qq_22527013/article/details/91371032

【注意】当k大于数组长度时,根据结果可见是需要将k视为k%nums.length再进行旋转

(也可先旋转整体数组,再重新旋转子数组)

 

代码:

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

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值