Leetcode 189. Rotate Array (rotated array)

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 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.

[Show hint]

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

Related Problem:reverse Words in a String II

Title tag: Array

The topic gives us an array and a K. Let's rotate the array k times.

Here's a neat way to do it:

The array is divided into two halves using the length-k of the array;

Reverse the left and right arrays;

Reverse Totals group.

To give an example:

  1 2 3 4 5 6 7 If k = 3, it becomes 5 6 7 1 2 3 4

  1 2 3 4 5 6 7 middle = 7-3 = 4, divided into 4 digits to the left, 3 digits to the right

  4 3 2 1 7 6 5 reverse the left and right, respectively.

  5 6 7 1 2 3 4 reverse the total group and you'll get the answer .

Java Solution:

Runtime beats 15.37%

Completion Date: 04/13/2017

Keywords: Array

Key points: using K to divide the array into two halves; reverse array of the left and right sides; Reverse Total Group

1  Public classSolution2 {3      Public voidRotateint[] Nums,intk)4     {5         if(Nums = =NULL|| Nums.length = = 0 | | K% Nums.length = = 0)6             return;7         8         intturns = k%nums.length;9         intMiddle = nums.length-turns;Ten          OneReverse (nums, 0, middle-1);//Reverse Left part AReverse (nums, middle, nums.length-1);//Reverse Right part -Reverse (nums, 0, nums.length-1);//Reverse Whole part -     } the      -      Public voidReverseint[] arr,intSinte) -     { -          while(S <e) +         { -             inttemp =Arr[s]; +Arr[s] =Arr[e]; AArr[e] =temp; at              -s++; -e--; -         } -     } -}

Resources:

Http://www.cnblogs.com/grandyang/p/4298711.html

Leetcode algorithm Topic List-Leetcode algorithms Questions list

Leetcode 189. Rotate Array (rotated 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.