leetcode解题系列:翻转数组
2015-07-23 11:19
405 查看
Q:Problem: 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] isrotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?a: 1、first method:新建一个数组,将数据保存存放结果。时间复杂度为:n,空间复杂度:n
public static void rotateArray(int array[], int k) { if(k <= 0) return; if(k > array.length) { k = k % array.length; } int result[] = new int[array.length]; for(int i=0; i<k; i++) { result[i] = array[array.length - k + i]; } int j =0; for(int i= k; i<array.length; i++) { result[i] = array[j]; j++; } System.arraycopy(result, 0, array, 0, array.length); }
2、second method : 类是冒泡算法:时间:n * k,空间:1
public static void bubbleRotate(int array[], int k) { for(int i=k; i< array.length; i++) { int tempValue = array[i]; for(int j = i ; j > 0; j --) { // int temp = array[j]; array[j] = array[j -1]; // array[j-1] = temp; } array[0] = tempValue; } }3、third method :翻转,时间为 n,空间为 1Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:1. Divide the array two parts: 1,2,3,4 and 5, 62. Rotate first part: 4,3,2,1,5,63. Rotate second part: 4,3,2,1,6,54. Rotate the whole array: 5,6,1,2,3,4
public static void reverseArray(int array[], int k) {reverse(array, 0, k-1);reverse(array, k, array.length -1);reverse(array, 0, array.length -1);}public static void reverse(int array[], int left, int right) {while (left < right) {int temp = array[left];array[left] = array[right];array[right] = temp;right--;left++;}ps:贴下代码 https://code.csdn.net/snippets/775491.git
相关文章推荐
- 动易2006序列号破解算法公布
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#动态调整数组大小的方法
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 详解Lua中的数组概念知识
- Perl中的列表和数组学习笔记
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- C#中数组初始化与数组元素复制的方法
- C#交错数组用法实例
- 超大数据量存储常用数据库分表分库算法总结
- PowerShell数组的一些操作技巧
- C#数据结构与算法揭秘二
- C#通过yield实现数组全排列的方法
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析