leetcode解题系列:翻转数组

Q:Problem: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?


a:

  1、first method:新建一个数组,将数据保存存放结果。时间复杂度为:n,空间复杂度:n

public static void rotateArray(int array[], int k) {
    if(k <= 0)
        return;
    if(k > array.length) {
        k = k % array.length;
    }

    int result[] = new int[array.length];

    for(int i=0; i<k; i++) {
        result[i] = array[array.length - k + i];
    }

    int j =0;
    for(int i= k; i<array.length; i++) {
        result[i] = array[j];
        j++;
    }

    System.arraycopy(result, 0, array, 0, array.length);
}
	2、second method : 类是冒泡算法:时间:n * k,空间:1
        
    public static void bubbleRotate(int array[], int k) {

        for(int i=k; i< array.length; i++) {
            int tempValue = array[i];
            for(int j = i ; j > 0; j --) {
//                int temp = array[j];
                array[j] = array[j -1];
//                array[j-1] = temp;
            }
            array[0] = tempValue;
        }

    }
  3、third method :翻转,时间为 n,空间为 1

Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:

1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Rotate first part: 4,3,2,1,5,6
3. Rotate second part: 4,3,2,1,6,5
4. Rotate the whole array: 5,6,1,2,3,4

    
public static void reverseArray(int array[], int k) {
    reverse(array, 0, k-1);
    reverse(array, k, array.length -1);
    reverse(array, 0, array.length -1);
}


public static void reverse(int array[], int left, int right) {

    while (left < right) {
        int temp = array[left];
        array[left] = array[right];
        array[right] = temp;
        right--;
        left++;
    }

        

ps:贴下代码

https://code.csdn.net/snippets/775491.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值