Leetcode-rotate array
来源:互联网 发布:java基础入门答案 编辑:程序博客网 时间:2024/06/16 12:51
旋转数组,
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].
非常简单,如果不考虑空间的话,很容易写出O(N)的空间复杂度的代码:
void rotate(int* nums, int numsSize, int k) { k = k%numsSize; int *tmpArr = (int *)malloc(sizeof(int)*numsSize); if(!tmpArr)return; int j=0; for(int i=numsSize-k;i<numsSize;i++) tmpArr[j++]=nums[i]; for(int m=0;m<numsSize-k;m++) tmpArr[j++]=nums[m]; for(int n=0;n<numsSize;n++) nums[n]=tmpArr[n];}
还有一种O(1)的空间复杂度的,考虑的想法是假设对于上面这个数组,我们可以先将前面一半的1,2,3,4翻转4,3,2,1;再将后面一部分5,6,7翻转成7,6,5,那么整个数组就是4,3,2,1,7,6,5,再将整个数组翻转一次就得到最终的答案了。
void rotate(int* nums, int numsSize, int k) { k = k%numsSize; reverse(nums,0,numsSize-k-1); reverse(nums,numsSize-k,numsSize-1); reverse(nums,0,numsSize-1);}void reverse(int *nums,int start,int end){ int i=start,j=end; while(i<j) { int tmp; tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; i++; j--; }}
阅读全文
0 0
- [leetcode][array] Rotate Array
- LeetCode[Array]: Rotate Image
- LeetCode:Rotate Array
- [LeetCode] Rotate Array
- *LeetCode-Rotate Array
- [LeetCode]189.Rotate Array
- Rotate Array - LeetCode - Java
- Rotate Array--Leetcode(Java)
- Leetcode--Rotate Array
- LeetCode: Rotate Array
- LeetCode Rotate Array
- Rotate Array(leetcode)
- leetcode Rotate Array
- Leetcode: Rotate Array
- [Leetcode]11 Rotate Array
- [LeetCode][189][Rotate Array]
- Leetcode:Rotate Array
- LeetCode: Rotate Array
- 面向对象程序设计上机练习二(函数模板)
- 使用FilenameFilter来得到指定文件后缀的文件目录集合
- 不让登QQ恶作剧小程序
- jQuery artDialog模态窗口
- 关于阅读书籍的一些想法
- Leetcode-rotate array
- 错误:HttpServlet was not found on the Java
- j控制frameset修改cols,页面的隐藏和打开。
- 行内元素竖直方向margin和padding以及盒子模型问题
- 华为机试-字典排序
- 【Tomcat】双击tomcat\bin文件夹中的startup.bat闪退,或者出现很多警告提示的解决方法
- Spring Cloud Stream (1)-代码篇
- 转换流与其子类之间的区别
- Improving Deep Neural Networks学习笔记(二)