"Leetcode" Rotate Array

Source: Internet
Author: User

Rotate Array

Rotate an array of n elements to the right by K steps.

For example, with n = 7 and k = 3, the array is [1,2,3,4,5,6,7] rotated to [5,6,7,1,2,3,4] .

Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

AC Code: (Python)

1 classSolution:2     #@param nums, a list of integers3     #@param k, num of steps4     #@return Nothing, please modify the Nums list in-place.5     defrotate (self, nums, K):6n =Len (nums)7K = k%N8nums[:] = nums[n-k:] + nums[:n-K]9         

One problem to note:

A little important thing to be cautious:

Can ' t be written as:

nums = nums[n-k:] + nums[:n-k]

On the OJ.

The previous one can truly change the value of an old nums, but the following one just changes its referenc E to a new nums not the value of old nums.

Because the topic requires:

@return Nothing, please modify the Nums list in-place.

"Leetcode" Rotate Array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.