给出反向数组查询

问题描述 投票:0回答:2

对于给定的整数数组,对该数组执行操作。按给定顺序应用所有操作后返回结果数组。每个操作包含两个索引。反转这些从零开始的索引之间的子数组(包括在内)。

1: arr 为: [1, 2, 3] 1: 操作为: [[0, 2], [1, 2], [0, 2]]

2: arr 为: [640, 26, 276, 224, 737, 677, 893, 87, 422, 30] 2: 操作为: [[0, 9], [2, 2], [5, 5] , [1, 6], [5, 6], [5, 9], [0, 8], [6, 7], [1, 9], [3, 3]] 任何人都可以帮助解决这个问题。

arrays reverse
2个回答
0
投票

像这样开始:

[1, 2, 3] -> [3, 2, 1]  # first: reverse array between index 0 and 2
          -> [3, 1, 2]  # then:  reverse array between index 1 and 2
etc.

我希望你明白了。


0
投票
public int[] performOperations(int[] arr, int[][] operations) {
      // iterate over all the operations
      for (int[] operation : operations) {
            int start = operation[0];
            int end = operation[1];
            //execute (reverse) the operation for given operation
            reverseSubarray(arr, start, end);
      }
      return arr;
}

void reverseSubarray(int[] arr, int start, int end) {
    while (start < end) {
       //swap the element
       int temp = arr[start];
       arr[start] = arr[end];
       arr[end] = temp;
       start++;
       end--;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.