Title Description:
Given an array, move the elements in the array to the right by the K position, where K is a non-negative number.
Example 1:
[1,2,3,4,5,6,7]K[5,6,7,1,2,3,4][7,1,2,3,4,5,6][6,7,1,2,3,4,5][5,6,7,1,2,3,4]
Example 2:
[-1,-100,3,99]k = 2 output: [3,99,-1,-100] Explanation: Rotate Right 1 steps: [99,-1,-100,3] Rotate Right 2 steps: [3,99,-1,-100]
Description
- Think of as many solutions as possible, at least three different ways to solve the problem.
- Requires an in-place algorithm with a space complexity of O (1).
Topic Analysis:
Shard Operations for lists
#!/usr/bin/env python#_*_ coding:utf-8 _*_classsolution ():defrotate (self, nums, K):""": Type Nums:list[int]: type k:int:rtype:void do not return anything, modify Nums in-place in Stead. """Nums_len=Len (nums) nums[:]= Nums[nums_len-k:] + Nums[:nums_len-K]if __name__=='__main__': Test_nums1= [-1,-100, 3, 99] Test_nums2= [1, 2, 3, 4, 5, 6, 7] My_solution=solution () my_solution.rotate (TEST_NUMS1,2) my_solution.rotate (TEST_NUMS2,3) Print(TEST_NUMS1)Print(TEST_NUMS2)
[Leetcode] Rotating an array