roatae array

/**
 * 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--;

        }
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TangGeeA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值