Swift Array Reverse Solution O(n)


  • 0
    Z
    func rotate(_ nums: inout [Int], _ k: Int) {
            let offset = k % nums.count
            self.reverse(&nums, 0, nums.count - offset - 1)
            self.reverse(&nums, nums.count - offset, nums.count - 1)
            self.reverse(&nums, 0, nums.count - 1)
        }
        
       func reverse(_ nums: inout [Int], _ left: Int, _ right: Int) {
            var l = left
            var r = right
            while (l < r) {
                let temp = nums[l]
                nums[l] = nums[r]
                nums[r] = temp
                l += 1
                r -= 1
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.