反向数组查询

Reverse Array Queries

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

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]]

这是我尝试过但似乎不起作用的方法

func performOperations(arr: [Int], operations: [[Int]]) -> [Int] {
// Write your code here
var arr = arr
var operations = operations
print("arr is : \(arr)")
print("operations is : \(operations)")
var v1 = 0
var v2 = 0
var count = 0
for (i, v) in operations.enumerated() {
    v1 = i
    for j in v {
        v2 = j
        if v1 > v2 {
            v2 = i
            v1 = j
        }
        
        // arr[v1] = arr[v2]
        // arr[v2] = arr[v1]
        
    }
    count = v2 - v1 + 1
}

for offset in 0..<count/2 {
    let f = v1 + offset
    let s = v2 - offset
    var o = arr[f]
    var o2 = arr[s]
    arr[s] = o
    arr[f] = o2
    
}
return arr

}

1: 2:

一个解决方案是每次操作将数组分成三部分,操作的第一个索引之前是什么,第二个索引之后是什么,中间是什么然后合并这三个部分被逆转了。

func performOperations(array: [Int], operations: [[Int]]) -> [Int] {
    var result = array

    for op in operations {
        let reversed = Array(result[op[0]...op[1]].reversed())
        let prefix = result[result.startIndex..<op[0]]
        let suffix = result[op[1] + 1..<result.endIndex]
        result = prefix + reversed + suffix
    }
    return result
}

此任务的一种实用方法是制作原始数组的可变副本,迭代每个操作以确保每个操作都有两个元素(索引)并且第一个索引小于第二个索引。然后你可以用它反转的子序列替换集合子范围:

func performOperations(arr: [Int], operations: [[Int]]) -> [Int] {
    var arr = arr
    operations.forEach {
        guard [=10=].count == 2, [=10=][0] < [=10=][1] else { return }
        arr.replaceSubrange([=10=][0]...[=10=][1], with: arr[[=10=][0]...[=10=][1]].reversed())
    }
    return arr
}

let arr = [640, 26, 276, 224, 737, 677, 893, 87, 422, 30]

let operations = [[0, 9], [2, 2], [5, 5], [1, 6], [5, 6], [5, 9], [0, 8], [6, 7], [1, 9], [3, 3]]

performOperations(arr: arr, operations: operations)  // [87, 422, 30, 737, 224, 677, 893, 640, 26, 276]