前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 189 Rotate Array

leetcode 189 Rotate Array

作者头像
流川疯
发布2019-01-18 16:05:56
4980
发布2019-01-18 16:05:56
举报

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

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

思想: 1.—567旋转—765 2.—1234旋转—4321 3.—整体旋转4321765—5671234

解决方案:

代码语言:javascript
复制
void reverse(int left,int right,int *array)
{
    int temp = 0;
    while(left<right)
    {

        temp = array[left];
        array[left]= array[right];
        array[right] = temp;
        left++;
        right--;
    }
}

void rotate(int* nums, int numsSize, int k)
{
    k = k%numsSize;//不知道为何这里要加上这一句?
    reverse(0,numsSize-k-1,nums);
    reverse(numsSize-k,numsSize-1,nums);
    reverse(0,numsSize-1,nums);
}

python解决方案:

代码语言:javascript
复制
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
    if not nums:
        return
    k%=len(nums)
    nums.reverse()
    self.reverse(nums,0,k-1)
    self.reverse(nums,k,len(nums)-1)


def reverse(self,nums,start,end):
    while start<end:
        nums[start],nums[end]=nums[end],nums[start]
        start+=1
        end-=1
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年05月04日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档