leetcode [Rotate Array]//待整理多种解法
2017-04-08 23:51
489 查看
public class Solution { //解法一:利用一个辅助数组可以要求,但不是很好,题目要求空间复杂度是O(1)的 public void rotate(int[] nums, int k) { //题目要求:Rotate an array of n elements to the right by k steps. //先处理k的值,鲁棒性 k = k % nums.length; int[] temp = new int[nums.length]; for(int i = nums.length - k, j = 0, shift = k; shift > 0; i++, j++, shift--){ temp[j] = nums[i]; //System.out.println((j + 1) + " : " + temp[j]); } for(int i = 0, j = k; i < nums.length - k; i++, j++){ temp[j] = nums[i]; //System.out.println((j + 1) + " : " + temp[j]); } //nums = temp;//最后把temp赋值给nums,这样不行,因为nums只是一个对象引用的拷贝,要修改nums只能直接去操作对象 for(int i = 0; i < nums.length; i++){ nums[i] = temp[i]; } } }
下面这种解法遇到长数组会很耗时
public class Solution { //解法二:Rotate an array of n elements to the right by k steps.将右边的k个数与左边的nums.length-k个数整体交换 //其实就是将数组看成一个环状的,要达到这样的目的其实就是将右边的k个数往左推nums.length-k格,观察例子总结 //因为将数组看成一个环状的,那么左边的k个数也从右开始向左推 //空间复杂度是O(1),只用到了一个temp,但时间复杂度是O(N*k) public void rotate(int[] nums, int k) { if(nums.length == 0) return; k = k % nums.length;//鲁棒性 for(int i = 0; i < nums.length - k; i++){//记录要移动的步数,左推nums.length-k格而不是k格 int temp = nums[0];//因为要移动,要存一个被覆盖的数 for(int j = 0; j < nums.length - 1; j++){ nums[j] = nums[j + 1]; } nums[nums.length - 1] = temp;//末尾元素 } } }
相关文章推荐
- leetcode[K-diff Pairs in an Array]//待整理多种解法
- leetcode [Convert Sorted Array to Binary Search Tree]//待整理多种解法
- leetcode[Array Partition I]//待整理多种解法
- leetcode [Balanced Binary Tree]//待整理多种解法
- leetcode [Pascal's Triangle II]//待整理多种解法
- leetcode [Contains Duplicate]//待整理多种解法
- leetcode[Binary Tree Paths]//待整理多种解法
- leetcode [Power of Two]//待整理多种解法
- [Leetcode][Rotate Array]一种对连续内存空间进行的循环移位的巧妙解法(O(1)的空间、O(n)的时间)
- leetcode [Happy Number]//待整理多种解法
- leetcode [Contains Duplicate II]//待整理多种解法
- leetcode [Isomorphic Strings]//待整理多种解法
- leetcode[Lowest Common Ancestor of a Binary Search Tree]//待整理多种解法
- leetcode [Best Time to Buy and Sell Stock II]//待整理多种解法
- leetcode [Implement Stack using Queues]//待整理多种解法
- leetcode之189. Rotate Array(C++解法)
- leetcode [Pascal's Triangle]//待整理多种解法
- leetcode [Intersection of Two Linked Lists]//待整理多种解法
- leetcode [Majority Element]//待整理多种解法
- leetcode [Implement Queue using Stacks]//待整理多种解法