/** * Created by tangtang on 15/6/22. * 问题描述 数组平移的问题 ,指定平移距离 后边超出范围的插入到数组前边 * 如 k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. */ public class RotateArray { /** * 有三种方法 * 1 用两个数组 * 2 平移n次 * 3 翻转 * */ public static char[] array={'a','b','c','d','e','f','g'}; public static void main(String[] args) { rotateArray3(array, 5); System.out.print(new String(array)); } /***************************1***********************/ public static char[] rotateArray1(char[] array,int order) { if (array==null) throw new IllegalArgumentException("错误参数"); if (order==0) return array; char[] desArray=new char[array.length]; /** * 前半部分 0-2 */ for (int i=0;i<array.length-order;i++) { desArray[order+i]=array[i]; } int j=0; for (int i=array.length-order;i<array.length;i++,j++) { desArray[j]=array[i]; } return desArray; } /***************************1***********************/ /** * 思想 最后的移动到最前边 移动order次 * @param array * @param order * @return */ public static char[] rotateArray2(char[] array,int order) { if (array==null) throw new IllegalArgumentException("错误参数"); if (order==0) return array; for (int i=0;i<order;i++) { for (int j = array.length - 1; j > 0; j--) { char temp = array[j]; array[j] = array[j - 1]; array[j-1] = temp; } } return array; } /** * * @param array * @param position 平移距离 * * 思路: * 翻转左部分 翻转右半部分 翻转所有 */ public static void rotateArray3(char[] array,int position) { position=position%array.length; if (array==null||position==0) throw new IllegalArgumentException("错误的参数"); int a = array.length - position; rotate(array,0,array.length-position-1); rotate(array,array.length-position,array.length-1); rotate(array,0,array.length-1); } public static void rotate(char[] array,int left,int right) { while (left<right) { char temp=array[left]; array[left]=array[right]; array[right]=temp; left++; right--; } } }
roatae array
最新推荐文章于 2025-08-18 23:59:06 发布