(leetcode) Rotate Array---inverse arrays

Source: Internet
Author: User

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

for example, With n  = 7 and k  = 3 , the Array [1,2,3,4,5,6,7"  is 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.

[Show hint]

Hint:
Could do it in-place with O (1) extra space?

Related Problem:reverse Words in a String II

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

Subscribe to see which companies asked this question


Problem Solving Analysis:

For this can be used to divide and conquer the method, you can use the given K value to divide the series into two parts,

Each part is reversed, and then the entire inverse is placed.

The principle of the algorithm to implement the inverse:

A ^= b

b ^= A

A ^= b

#-*-Coding:utf-8-*-__author__ = ' Jiuzhang ' class solution (object):    def rotate (self, nums, K):        n = Len (nums) 
   
    k%= n        self.reverse (nums, 0, N-k)        self.reverse (Nums, N-k, N)        self.reverse (nums, 0, N)    def reverse (sel F, Nums, start, end): For        x in range (start, (start + end)/2):            nums[x] ^= Nums[start + end-x-1]            Nums[star T + end-x-1] ^= nums[x]            nums[x] ^= Nums[start + end-x-1]
   






(leetcode) Rotate Array---inverse arrays

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.