Q189 Rotate Array
Solution: Reversing
If we have an array as blow and k = 3
1, 2, 3, 4, 5, 6
Reverse the whole array and we get
6, 5, 4, 3, 2, 1
Reverse the first k element
4, 5, 6, 3, 2, 1
Reverse the elements from k+1 ~ n
4, 5, 6, 1, 2, 3 this is what we are expecting
https://github.com/Sylvia-YiyinShen/Algorithm/blob/master/TwoPointers/Q189RotateArray.playground/Contents.swift
No comments:
Post a Comment