Rotate Array
2015-12-09 10:41
106 查看
问题描述
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?
算法
代码一public void rotate(int[] nums, int k) { int n = nums.length; int temp; k = k % n; for (int i = 0; i < n / 2; i++) { temp = nums[i]; nums[i] = nums[n - 1 - i]; nums[n - 1 - i] = temp; } for (int i = 0; i < k / 2; i++) { temp = nums[i]; nums[i] = nums[k - 1 - i]; nums[k - 1 - i] = temp; } for (int i = 0; i < (n - k) / 2; i++) { temp = nums[k + i]; nums[k + i] = nums[n - 1 - i]; nums[n - 1 - i] = temp; } }
注意k可能会比n大,所以将k模n。
代码二
public void rotate1(int[] nums,int k){ int n=nums.length; k=k%n; reverse(nums,0,n-1); reverse(nums,0,k-1); reverse(nums,k,n-1); } private void reverse(int[] nums,int s,int e){ int temp; while(s<e){ temp=nums[s]; nums[s]=nums[e]; nums[e]=temp; s++; e--; } } private void reverse1(int[] nums,int m,int n){ while(m<n){ nums[m]^=nums ; nums ^=nums[m]; nums[m]^=nums ; m++; n--; } }
代码二的思想和代码一的思想一样,优点是把三次反转写成一个函数。另外两个值交换可以用异或运算。
代码三
//https://leetcode.com/discuss/28501/my-c-solution-o-n-time-%26%26-o-1-space public void rotate2(int[] nums, int k) { int n = nums.length; k = k % n; int i = 0; int nowIndex = 0, tmp1, tmp2 = nums[0]; for (int j = 0; j < n; j++) { tmp1 = tmp2; nowIndex = (nowIndex + k) % n; tmp2 = nums[nowIndex]; nums[nowIndex] = tmp1; if (nowIndex == i && i < n - 1) { i++; nowIndex = i; tmp2 = nums[nowIndex]; } } }
相关文章推荐
- 跟我一起玩Win32开发(1):关于C++的几个要点
- Incompatible integer topointer conversion assigning to 'BOOL *' (aka 'signed char *') from'BOOL' (a
- CListCtrl控件实现点击单行选中当前CheckBox点击CheckBox实现多选功能
- redis windows
- Tomcat Xms Xmx PermSize MaxPermSize 区别 及 java.lang.OutOfMemoryError: PermGen space 解决
- windows下安装python及django的开发环境
- Spring:整合Struts1
- SQLite数据库增删改查操作
- 睡得多,会变丑变痴
- 数字图像处理作业之MATLAB操作现象思考
- 网站压力测试
- 经典算法: Bit-Map 处理海量数据(上亿数据)
- JS隔行变色
- js 实时监听input中值变化 【转】
- Install LaTeX in Ubuntu Linux
- MySQL中使用SQL语句查看某个表的编码
- 页面总结
- iOS开发之单例模式
- 道家眼中的色情伤害
- 各大网站搜索引擎提交网址