rotate array
来源:互联网 发布:js 判断是function 编辑:程序博客网 时间:2024/05/21 07:13
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.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
#include<iostream>using namespace std;class Solution {public:void rotate(int nums[], int n, int k) /* solution one */{ //时间复杂度为O(k*n);空间复杂度O(1)int temp;for (int i = 0; i < k; i++){temp = nums[n - 1];for (int j = n - 2; j >= 0; j--){nums[j+1] = nums[j];}nums[0] = temp;}}void rotate2(int nums[], int n, int k) /* solution two */{k = k%n;int *temp = new int[n];memcpy(temp, nums + n - k, sizeof(int)*k);memcpy(temp+k,nums,sizeof(int)*(n-k));memcpy(nums, temp, sizeof(int)*n);delete[] temp;/*void *memcpy(void *dest, const void *src, size_t n);c和c++使用的内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中。注意:dest和src在内存的位置,可能会产生覆盖的情况。*/}
void reverse(int nums[], int start, int end) { int i = 0; while (start < end) {int tmp = nums[start];nums[start] = nums[end];nums[end] = tmp;start++;end--; } } void rotateArray3(int nums[],int n, int k) { //最优效率的方法,时间复杂度为O(n);空间复杂度为O(1) reverse(nums, 0, n - k-1 ); reverse(nums, n - k, n-1); reverse(nums, 0, n - 1); }
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
- 孔浩老师 jUnit 视频教程学习笔记(第1讲)
- 1002求最值
- 雪花飘落-动画制作(UIImage+NSTimer定时器)
- IOS路径沙盒文件管理
- 正则表达式
- rotate array
- MM_ISOTROPIC与MM_ANISOTROPIC映射模式
- 《iOS总结》传值方式-MickyChiang
- VC中的RegisterHotKey函数与HotKey控件(CHotKeyCtrl)
- ffmpeg编译
- 设备坐标与逻辑坐标相互转换的两个函数
- XCode生成文档
- 墨卡托、高斯克吕格和UTM投影
- 玩转大数据系列之Apache Pig如何与MySQL集成(三)