Swift Solution


  • 0
    S
    func rotate(_ nums: inout [Int], _ k: Int) {
    // If the shift value is greater than the count, wrap it around.
        let shift = k > nums.count ? abs(nums.count - k) : k
        
        guard nums.count > 1, shift > 0 else { return }
        
        let lastIndex = nums.count - 1
    
    // Add one to make sure its the correct index.
        let shiftFrom = lastIndex - shift + 1
        
        let backArray = Array(nums[shiftFrom...lastIndex])
        let frontArray = Array(nums[0..<shiftFrom])
    
        nums = backArray + frontArray
    }
    

Log in to reply
 

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