码迷,mamicode.com
首页 > 其他好文 > 详细

Left Shift Array with O(l) time complexity and O(1) space complexity

时间:2015-01-04 07:37:58      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/4200271.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!