首页 > 代码库 > Left Shift Array with O(l) time complexity and O(1) space complexity
Left Shift Array with O(l) time complexity and O(1) space complexity
Algorithm 1:
public static void main(String[] args) { int[] a = new int[]{1,2,3,4,5,6,7,8,9,10,11,12}; shiftN2(a, 1); System.out.println(Arrays.toString(a)); } public static void shiftN2(int[] a, int n) { n = n%a.length; swapArray(a, 0, n-1); swapArray(a, n, a.length-1); swapArray(a, 0, a.length-1); } private static void swapArray(int[] a, int from, int to) //[from, to] { int temp; while(from<to) { temp = a[from]; a[from++] = a[to]; a[to--] = temp; } }
Algorithm 2:
public static void main(String[] args) { int[] a = new int[]{1,2,3,4,5,6,7,8,9,10,11,12}; for(int i = 0;i<a.length; ++i) { int[] aCopy = Arrays.copyOf(a, a.length); shiftN(aCopy, i); System.out.println(Arrays.toString(aCopy)); } } public static void shiftN(int[] a, int n) { int l = a.length; n = n%l; if(n==0) return; int changed = 0; int i = 0; while(changed<l) { int start = 0 -n + l + i; int from = i; int to = start; int temp = a[to]; while(from != start) { a[to]=a[from]; ++changed; to = from; from = (from + n)%l; } a[to]=temp; ++i; ++changed; } }
Left Shift Array with O(l) time complexity and O(1) space complexity
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。