我们可以将数组中的元素截取成不同的段,然后对它们分别进行旋转并拼接在一起形成一个新的数组。
Python 代码示例:
def rotate_array(arr, n):
    length = len(arr)
    # 如果 n 大于数组长度,需要对 n 取模
    n = n % length 
    # 将数组切割成两段,各自进行翻转
    first_part = arr[:length-n][::-1]
    second_part = arr[length-n:][::-1]
    # 拼接两段并逆向输出
    return (first_part + second_part)[::-1]
arr = [1, 2, 3, 4, 5]
n = 2
print(rotate_array(arr, n))  # 输出 [4, 5, 1, 2, 3]
Java 代码示例:
public static int[] rotateArray(int[] arr, int n) {
    int length = arr.length;
    // 如果 n 大于数组长度,需要对 n 取模
    n = n % length; 
    int[] result = new int[length];
    // 将数组切割成两段,各自进行翻转
    int[] firstPart = Arrays.copyOfRange(arr, 0, length - n);
    int[] secondPart = Arrays.copyOfRange(arr, length - n, length);
    reverseArray(firstPart);
    reverseArray(secondPart);
    // 合并两段翻转后的数组,然后再次翻转
    System.arraycopy(secondPart, 0, result, 0, n);
    System.arraycopy(firstPart, 0, result, n, length - n);
    reverseArray(result);
    return result;
}
// 翻转数组
public static void reverseArray(int[] arr) {
    int left = 0, right = arr.length - 1;
    while (left < right) {
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}
public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5};
    int n = 2;
    int[] result = rotateArray(arr,n);
    System.out.println(Arrays.toString(result));  // 输出 [4, 5, 1, 2, 3]
}