LeetCode – 189. Rotate Array

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.

This problem is quite interesting. Note that k might be greater than n. The approach is as follows:

  1. First invert
  2. Invert 0-k
  3. Invert the second half

Similar questions:Reverse Words in a String II

public class Solution { public void rotate(int[] nums, int k) { while(k>nums.length){ k -= nums.length; } rev(nums,0,nums.length-1); rev(nums,0,k-1); rev(nums,k,nums.length-1); } public void rev(int[] nums,int start,int end){ while(start 

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「LeetCode – 189. Rotate Array」

134
0 0 134

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top