Leetcode Problem Solving rotate array original problem
Converts a number in an array to the right-hand K-bit, which means that all numbers move backward through the K-bit, and the number at the end moves to the beginning.
Note the point:
- Use as many methods as possible to solve
- Provides a solution that requires only O (1) space
Example:
Input: Nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Thinking of solving problems
Solution One, make a note of the last number, the other number is shifted backward one, and finally put the recorded number at the beginning, so K times. The spatial complexity of the solution is O (1) and time complexity O (kn).
Solution two, applying for an array of equal size, will be shifted after the result exists in the new application array. The spatial complexity of the solution is O (n) and the time complexity is O (n).
Solution Three, the right-handed K number has an equivalent operation, is to flip the first k number, the remaining number is also flipped, and finally the entire array is flipped. The array now has the same result as a right-handed K number. The spatial complexity of the solution is O (1) and the time complexity is O (n).
Note that K may be larger than the length of the array n, we can take K to n remainder, because the right-hand n number is equivalent to no change, can reduce the computational amount.
AC Source
class solution(object): def rotate(self, nums, k): "" " : Type Nums:list[int]: type k:int:rtype:void do not return anything, modify Nums in-place instead. """ def reverse(nums, start, end): whileStart < End:nums[start], nums[end] = Nums[end], Nums[start] start + =1End-=1n = Len (nums) k%= n Reverse (nums,0, N-k-1) Reverse (nums, n-k, N-1) Reverse (Nums,0N1)if__name__ = ="__main__": Nums = [1,2,3,4,5,6,7] Solution (). Rotate (Nums,Ten)assertNums = = [5,6,7,1,2,3,4]
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Rotate Array