Rotate Array
来源:互联网 发布:微软办公软件2007 编辑:程序博客网 时间:2024/06/09 16:10
Rotate Array
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.
<pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 24.44444465637207px; line-height: 25.98958396911621px;">class Solution {public: void rotate(vector<int>& nums, int k) { int temp; for(int i=0;i<k;i++) { temp=nums[nums.size()-1]; for(int j=nums.size()-1;i>0;i--) { nums[i]=nums[i-1]; } nums[0]=temp; } }};
如果是k步,那么就是把后面k个放到前面了嘛。
我们先把整个数组reverse,然后把前面的reverse回来,再把后面的reverse回来
对于AB我们要通过reverse操作得到BA
那么先把AB reverse一次得到reverse(B)reverse(A)
然后再把reverse(B),reverse(A)分别reverse一次就得到了BA
class Solution {public: void rotate(vector<int>& nums, int k) { k=k%(nums.size()); int n=nums.size(); int a[n]; for(int i=0;i<nums.size();i++) { a[i]=nums[i]; } reverse(a, a + n); reverse(a, a + k); reverse(a + k, a + n); for(int i=0;i<n;i++) { nums[i]=a[i]; } }};
class Solution{public:void swap(int * a,int * b){int temp = *a;*a = *b;*b = temp;}void rotate(vector<int> & nums,int k){int length = nums.size();int l = length - (k % length);int r = k % length;for(int i = 0,j = l - 1;i < j;i++,j--)swap(&nums[i],&nums[j]);for(int i = l,j = length - 1;i < j;i++,j--)swap(&nums[i],&nums[j]);for(int i = 0,j = length - 1;i < j;i++,j--)swap(&nums[i],&nums[j]);}};
0 0
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- rotate array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Objc-C 知识点回顾 七 block
- cygwin gcc 动态链接库问题
- 使用 Jersey 和 Apache Tomcat 构建 RESTful Web 服务
- No Dialect mapping for JDBC type: -1 问题解决
- Eclipse读取xml中文乱码问题解决
- Rotate Array
- android性能测试
- windows删除一个目录下的文件c代码
- 安卓微信浏览器加border-radius出现模糊(锯齿)
- Observer(观察者)设计模式
- jQuery HTML节点元素修改、追加的方法
- leetcode 009 Palindrome Number(难易度:Easy)
- 基于HttpURLConnection 的Get\Post封装(一)
- jQuery操作表格