数组旋转
返回将一维数组向右旋转k个位置的结果。比如,一维数组{1,2,3,4,5},k=2时,返回结果是{4,5,1,2,3},要求常数级空间复杂度,允许修改原有数组。
/** * 4.数组旋转 **/ class solution { public static int[] reverseArray(int[] A,int k) { if(A==null||k>=A.length) return A; reverse(A,0,A.length-1); reverse(A,0,k-1); reverse(A,k,A.length-1); return A; } public static void reverse(int[] A,int start,int end) { while(start<end) { int temp = A[start]; A[start] = A[end]; A[end] = temp; start++; end--; } }