//Given an array, rotate the array to the right by k steps, where k is non-negative. // Input: nums = [1,2,3,4,5,6,7], k = 3 // Output: [5,6,7,1,2,3,4] // Explanation: // rotate 1 steps to the right: [7,1,2,3,4,5,6] // rotate 2 steps to the right: [6,7,1,2,3,4,5] // rotate 3 steps to the right: [5,6,7,1,2,3,4] //SOLUTION: // Reverse array, find the split point and reverse two separate arrays from left and right side. func rotate(_ nums: inout [Int], _ k: Int) { // Exctact the length of array from steps count. // It's unnecessary to rotate array by steps that equal the array length, because we'll get the same array. let splitPoint = k % nums.count nums.reverse() reverse(&nums, start: 0, end: splitPoint - 1) reverse(&nums, start: splitPoint, end: nums.count - 1) } func reverse(_ nums: inout [Int], start: Int, end: Int) { var s = start var e = end while s < e { var temp = nums[s] nums[s] = nums[e] nums[e] = temp s += 1 e -= 1 } }