Rotating an array in place

April 13, 2010 in Uncategorized

Rotate a one-dimensional array of n elements to the right by k steps. 
For instance, with n=7 and k=3, the array {a, b, c, d, e, f, g} is rotated to {e, f, g, a, b, c, d}.

In my previous post we discussed about finding an element in a rotated array. You might ask, how do we rotate an array?

The straight forward way is to allocate a temporary array of size n, and then copy elements starting from index k to the new array, and copy it back to the old array. This is highly inefficient because:

    1. It needs extra space to store a temporary array (O(n) space).
    1. It involves back-and-forth copying, a total of 2*n copy operations.

So, the question is, can we do this more efficiently, preferably an in-place rotation method.

The answer is of course, yes. This is a trick so important that it becomes one of the frequently asked interview questions. An in-depth discussion is in Programming Pearls, one of the must-read book in Computer Science.

The trick is to do three reverse operation. One for the entire string, one from index 0 to k-1, and lastly index k to n-1. Magically, this will yield the correct rotated array, without any extra space! (Of course, you need a temporary variable for swapping).

void reverse_string(char* str, int left, int right) {
  char* p1 = str + left;
  char* p2 = str + right;
  while (p1 < p2) {
    char temp = *p1;
    *p1 = *p2;
    *p2 = temp;
    p1++;
    p2--;
  }
}

void rotate(char* str, int k) {
  int n = strlen(str);
  reverse_string(str, 0, n-1);
  reverse_string(str, 0, k-1);
  reverse_string(str, k, n-1);
}
时间: 2024-08-07 18:10:18

Rotating an array in place的相关文章

LeetCode 396. Rotate Function

Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. Ca

[LeetCode] Rotate Function 旋转函数

Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. Ca

Leetcode: Rotate Function

Given an array of integers A and let n to be its length. Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. Ca

490 - Rotating Sentences

 Rotating Sentences  In ``Rotating Sentences,'' you are asked to rotate a series of input sentences 90 degrees clockwise. So instead of displaying the input sentences from left to right and top to bottom, your program will display them from top to bo

[GeeksForGeeks] Cyclically rotate an array by one

Given an array of integers, write a program that cyclically rotates the array by one. Example: given {1,2,3,4,5}, your program should rotate the array to {5,1,2,3,4} Algorithm: 1. save the last element in a temp variable. 2. starting from the last el

PHP Warning: array_multisort(): Array sizes are inconsistent

array_multisort() 函数返回排序数组.您可以输入一个或多个数组.函数先对第一个数组进行排序,接着是其他数组,如果两个或多个值相同,它将对下一个数组进行排序. 遇到这报错是两个数组对比不一致导致的, 如果是一维数组与二维数组进行排序可以用以下方法解决: 使用这个方法,会比较麻烦些,要将age提取出来存储到一维数组里,然后按照age升序排列.具体代码如下: 复制代码代码如下: $ages = array();foreach ($users as $user) {    $ages[]

详解go语言的array和slice 【二】

上一篇  详解go语言的array和slice [一]已经讲解过,array和slice的一些基本用法,使用array和slice时需要注意的地方,特别是slice需要注意的地方比较多.上一篇的最后讲解到创建新的slice时使用第三个索引来限制slice的容量,在操作新slice时,如果新slice的容量大于长度时,添加新元素依然后使源的相应元素改变.这一篇里我会讲解到如何避免这些问题,以及迭代.和做为方法参数方面的知识点. slice的长度和容量设置为同一个值 如果在创建新的slice时我们把

JavaScript的进阶之路(三)引用类型之Object类型和Array类型

引用类型 Object类型 function a(num){ if(num>3){ a(--num); } console.log(num); } a(5); //如何创建对象的实例 var obj1= new Object(); console.log(obj1); obj1.name="吴琼"; obj1.age=28; console.log(obj1.name+" "+obj1.age); //对象字面量语法 ,有点封装的感觉 var obj2 = {

LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,