【LeetCode & 剑指offer刷题】数组题9:旋转数组(189. Rotate Array)

【LeetCode & 剑指offer刷题】数组题9:旋转数组(189. Rotate Array)

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

189. Rotate Array(相当于循环右移k位)

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?
相关题目: 循环左移
//方法一:使用额外的数组,索引i用i+k替换,然后把组织好的数组复制过去
// O(n), O(n)
/*class Solution
{
public:
    void rotate(vector<int>& a, int k)
    {
        vector<int> temp(a);
        int n = a.size();
        for(int i = 0; i<n; i++)
        {
            temp[(i+k)%n] = a[i]; //进行题意的rotated
        }
       
        a = temp; //将数据复制过去
    }
};*/
/*
方法二:多次反转法
Original List                   : 1 2 3 4 5 6 7
After reversing all numbers     : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result
分析:O(n) O(1)
*/
#include <algorithm>
class Solution
{
public :
    void rotate ( vector < int >& a , int k )
    {
        k %= a . size (); //以免k过大
       
        reverse ( a . begin (), a . end ()); //反转所有元素
        reverse ( a . begin (), a . begin ()+ k ); //反转前k个元素
        reverse ( a . begin ()+ k , a . end ()); //反转剩余元素(注意reverse反转区间为前闭后开,故这里为a.begin()+k)
    }
};
//方法三:使用循环替代,略
 
 
 

 

posted @ 2019-01-05 14:09 wikiwen 阅读( ...) 评论( ...) 编辑 收藏
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值