博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
189. Rotate Array
阅读量:4687 次
发布时间:2019-06-09

本文共 1087 字,大约阅读时间需要 3 分钟。

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.

 

Solution 1: note that line 6 uses k%size. the time complexity of erase is O(n), so the worst total time could be O(n^2)

1 class Solution { 2 public: 3     void rotate(vector
& nums, int k) { 4 int size=nums.size(); 5 int i=0; 6 while (i

Solution 2:reverse the previous n-k nums and then reverse the later k nums. Finally reverse all. O(n)

1 2 3 4 5 6 7 

4321567

4 3 2 1 7 6 5

5 6 7 1 2 3 4

1 class Solution { 2 public: 3     void rotate(vector
& nums, int k) { 4 if (nums.empty() || (k %= nums.size()) == 0) return; 5 int n = nums.size(); 6 reverse(nums.begin(), nums.begin() + n - k); 7 reverse(nums.begin() + n - k, nums.end()); 8 reverse(nums.begin(), nums.end()); 9 }10 };

 

转载于:https://www.cnblogs.com/anghostcici/p/6917120.html

你可能感兴趣的文章
Kruskal算法(转)
查看>>
CSS3 Media Queries实现响应式布局
查看>>
【34.14%】【BZOJ 3110】 [Zjoi2013]K大数查询
查看>>
【 henuacm2016级暑期训练-动态规划专题 A 】Cards
查看>>
第五篇:白话tornado源码之褪去模板的外衣
查看>>
设备常用框架framework
查看>>
bootstrap模态框和select2合用时input无法获取焦点(转)
查看>>
快速转移数据的要领
查看>>
windows情况下的oracle效力
查看>>
*nix-style:定制 bash 提示符
查看>>
Informix IDS 11系统解决(918查验)认证指南,第 7 部分: IDS复制(7)
查看>>
解决Charles Response 中文乱码
查看>>
Spring Boot 分布式Session状态保存Redis
查看>>
Unity笔记——1.Unity3D脚本基础
查看>>
List分组 用于客服对话分组场景
查看>>
mybatis的二表联合查询
查看>>
全排列与 康托展开
查看>>
eclipse不格式化注释
查看>>
C语言结构体初始化(转载)
查看>>
系统剪切板的使用UIPasteboard
查看>>