首页 > 代码库 > 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