Skip to content

Instantly share code, notes, and snippets.

@EvolverSwiftUI
Forked from MickhailP/RotateArray.swift
Created November 27, 2022 08:54
Show Gist options
  • Save EvolverSwiftUI/8e4bec79f23f98718a3e91a88d903c61 to your computer and use it in GitHub Desktop.
Save EvolverSwiftUI/8e4bec79f23f98718a3e91a88d903c61 to your computer and use it in GitHub Desktop.
RotateArray
//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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment