leetcode面試經典150題- 189. 輪轉陣列

MoonBeautiful發表於2024-08-13

https://leetcode.cn/problems/rotate-array/description/?envType=study-plan-v2&envId=top-interview-150

go

package leetcode150

import "testing"

func TestRotate(t *testing.T) {
    nums := []int{1, 2}
    rotate2(nums, 3)
    for _, num := range nums {
        print(num)
        print(" ")
    }
}

func rotate(nums []int, k int) {
    if len(nums) == 0 {
        return
    }
    k = k % len(nums)
    nums2 := make([]int, k)
    i := 0
    for j := len(nums) - k; j < len(nums); j++ {
        nums2[i] = nums[j]
        i++
    }
    i = len(nums) - k - 1
    j := len(nums) - 1
    for i >= 0 {
        nums[j] = nums[i]
        i--
        j--
    }
    i = 0
    for i < k {
        nums[i] = nums2[i]
        i++
    }
}

func rotate2(nums []int, k int) {
    if len(nums) == 0 {
        return
    }
    k = k % len(nums)

    for k > 0 {
        lastVal := nums[len(nums)-1]
        for i := len(nums) - 1; i > 0; i-- {
            nums[i] = nums[i-1]
        }
        nums[0] = lastVal
        k--
    }
}

java

package leetcode150;

import org.junit.Test;

public class a6_189_rotate {

    @Test
    public void test() {
        int[] nums = {1,2,3,4,5,6,7};
        rotate(nums, 3);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }

    public void rotate(int[] nums, int k) {
        if (nums.length == 0) return;
        k %= nums.length;
        int[] nums2 = new int[k];
        int i = nums.length - k;
        int j = 0;
        for (; i < nums.length; i++) {
            nums2[j] = nums[i];
            j++;
        }

        i = nums.length - 1;
        while (i - k >= 0) {
            nums[i] = nums[i - k];
            i--;
        }

        j = 0;
        while (j < k) {
            nums[j] = nums2[j];
            j++;
        }
    }

    // 超時
    public void rotate2(int[] nums, int k) {
        if (nums.length == 0) return;
        k %= nums.length;
        while (k > 0) {
            int lastVal = nums[nums.length - 1];
            for (int i = nums.length - 1; i > 0; i--) {
                nums[i] = nums[i - 1];
            }
            nums[0] = lastVal;
            k--;
        }
    }
}

相關文章