leetcode_Rotate Array
来源:互联网 发布:excel筛选重复数据 编辑:程序博客网 时间:2024/04/30 00:12
描述:
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.
[show hint]
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
思路:
当然,一个很简单且容易想到的思路就是直接循环移位k位即可,但每次都要移动n个元素,即总共需要移动k*n个元素
和Reverse Words in a String II题目类似,还有一种通过改变固定数目的元素就可以实现移位数组的功能,即先将1~len-k,len-k~len之间的元素逆置,最后将1~len之间的元素逆置,可以实现最后的旋转数组的目的。
代码:
public void rotate(int[] nums, int k) { if(nums==null) return;int len=nums.length;k=k%len;if(k==0) return;int mid=len-k;int temp=0;int index=mid/2;for(int i=0;i<index;i++){ temp=nums[i]; nums[i]=nums[mid-1-i]; nums[mid-1-i]=temp;}index=(mid+len)/2;for(int i=mid;i<index;i++){ temp=nums[i]; nums[i]=nums[mid+len-1-i]; nums[mid+len-1-i]=temp;}index=len/2;for(int i=0;i<index;i++){ temp=nums[i]; nums[i]=nums[len-1-i]; nums[len-1-i]=temp;} }
0 0
- leetcode_Rotate Array
- Leetcode_Rotate Array
- LeetCode_Rotate Image
- Leetcode_rotate-list
- Leetcode_rotate-image
- Leetcode_Rotate Image
- LeetCode_Rotate List
- LeetCode_Rotate Image
- leetcode_Rotate Image
- LeetCode_rotate-image
- array
- Array#-
- Array#[]
- Array#<<
- Array
- array
- Array
- array
- Linux--进程组、会话、守护进程
- SB tree——A temporal aggregation data structure
- hdu 5299 ZCC loves strings
- .Net中的早期绑定和后期绑定(二)
- 局部变量在编译时就确定地址吗
- leetcode_Rotate Array
- 学习ASP.NET MVC5框架揭秘笔记-ASP.NET MVC是如何运行的(五)
- LintCode-木材加工
- git-基本知识
- Json转换利器Gson之实例二-Gson注解和GsonBuilder
- HTML中制作两列布局使用浮动
- SQLite应用详解
- 四十八、多态性:虚函数
- 快递物流第三方接口