Leetcode: Rotate Array, leetcoderotate

Source: Internet
Author: User

Leetcode: Rotate Array, leetcoderotate

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 you can, there are at least 3 different ways to solve this problem.[show hint]Hint:Could you do it in-place with O(1) extra space?

The idea of Naive is to save a copy of the original array and divide the original array into the first len-k elements and the last k elements, place the last k Elements in front of the first len-k elements. O (N) space is required for this operation.

In-place:

(1) reverse the array;

(2) reverse the first k elements;

(3) reverse the last n-k elements.

The first step moves the first n-k elements to the end, and moves the last k elements to the front. The next two steps put elements in the right order.

 1 public class Solution { 2     public void rotate(int[] nums, int k) { 3         int len = nums.length; 4         k %= len; 5         reverse(nums, 0, len-1); 6         reverse(nums, 0, k-1); 7         reverse(nums, k, len-1); 8     } 9     10     public void reverse(int[] nums, int l, int r) {11         while (l <= r) {12             int temp = nums[l];13             nums[l] = nums[r];14             nums[r] = temp;15             l++;16             r--;17         }18     }19 }

Note that there are 4th rows, and the right shift offset k may be larger than the array length len, so k % = len;

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.