1.1数组和链表:189. Rotate Array(Leetcode)
来源:互联网 发布:数据库一致性错误修复 编辑:程序博客网 时间:2024/06/14 13:58
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.
大意:在长度为n的数组中,将后k位数以固定的相对顺序旋转至数组开头。
解法一:
比较容易想到:复制一个和nums一样的数组,然后利用映射关系i -> (i+k)%n来交换数字。代码如下:
public void rotate(int[] nums, int k) { int n = nums.length; int[] newNums = new int[n]; for(int i = 0;i < n;i ++) newNums[i] = nums[i]; for(int i = 0;i < n;i ++){ nums[(i + k) % n] = newNums[i]; } }由于提示中提醒空间复杂度为O(1)而上述代码为O(N),所以我们可以延续上面的思路,用O(1)的空间复杂度来解决问题:下图展示nums元素的变化情况。
1 2 3 4 5 6 7
1 2 3 1 5 6 7
1 2 3 1 5 6 4
1 2 7 1 5 6 4
1 2 7 1 5 3 4
1 6 7 1 5 3 4
1 6 7 1 2 3 4
5 6 7 1 2 3 4
代码如下
解法二:
public void rotate(int[] nums, int k) { if(nums.length == 0 || (k %= nums.length) == 0) return; int n = nums.length; int i = 0,start = 0,temp = nums[i],count = 0; while(count ++ < n){ int index = (i + k) % n; int temp2 = nums[index]; nums[index] = temp; temp = temp2; i = index; if(index == start){ i ++;start++; temp = nums[i]; } } }
第一行代码确保k在取余n为0的时候(多表现为k与n相等),可以直接返回,因为此时数组不做任何变化,如果不返回会造成后续代码的数组脚标越界,定义count来确定是否每个元素都发生了变化,定义temp来存储在转换过程中被替换位置的值,因为先后顺序的关系这个值必须先由temp2存储(因为temp需要先将她的值赋给当前位置)之后再由temp2赋给temp,temp应定义在循环外,因为他需要在各次循环中通信。判断index == start是为了防止n能够被k整除时候造成的无限循环。
剩余解法见http://www.cnblogs.com/grandyang/p/4298711.html,因有几个解法尚未理解,在此不做阐述。
阅读全文
0 0
- 1.1数组和链表:189. Rotate Array(Leetcode)
- LeetCode 189. Rotate Array(旋转数组)
- leetcode 189. Rotate Array-旋转数组
- LeetCode#189. Rotate Array(数组循环移位)
- leetcode 189. Rotate Array旋转数组
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode 189 Rotate Array(旋转数组)
- (LeetCode)Rotate Array --- 逆置数组
- leetcode:Rotate Array旋转数组
- 【LeetCode】Rotate Array 旋转数组
- Rotate Array 数组旋转 leetcode
- leetcode Rotate Array 旋转数组
- [LeetCode]189.Rotate Array
- [Leetcode] 189.Rotate Array
- LeetCode 189. Rotate Array
- 【LeetCode】189.Rotate Array
- [leetcode] 189.Rotate Array
- 【leetcode】189. Rotate Array
- XBRL类型报文的开发(小demo)
- CentOS 64位 安装openfire
- PAT 1009. 说反话 (20)
- DDMS进行Pull文件报错Failed to pull selection: open failed: Permission denied的解决方法
- c语言大数乘法各位相加问题
- 1.1数组和链表:189. Rotate Array(Leetcode)
- java连接数据库方式(三):MyBatis 与Spring整合
- 剑指offer[一]:二维数组中的查找(java和c++版本)
- 黑马java全套视频教程 黑马javaee传智播客 32期 28期+20套项目
- DOS窗口的一些简单介绍
- python文件和异常
- c++stl的bitset位集合容器
- HTML5拖拽
- 怎么解决VMware“该虚拟机似乎正在使用中”问题