相关疑难解决方法(0)

在数组C++中移位元素

我已经为我的堆栈对象类开发了一个名为"rotate"的方法.我所做的是,如果堆栈包含元素:{0,2,3,4,5,6,7}我需要向前和向后旋转元素.

如果我需要向前旋转2个元素,那么我们将在数组中有{3,4,5,6,7,0,2}.如果我需要向后旋转,或者-3个元素,那么,查看原始数组,{5,6,7,0,2,3,4}

所以我开发的方法运行正常.它只是非常无效的IMO.我想知道我是否可以使用mod运算符包围数组?或者,如果它们是无用的代码,我还没有意识到,等等.

我想我的问题是,我该如何简化这种方法?例如使用较少的代码.:-)

void stack::rotate(int r)
{
    int i = 0;
    while ( r > 0 ) // rotate postively.
    {
        front.n = items[top+1].n;
        for ( int j = 0; j < bottom; j++ )
        {
            items[j] = items[j+1];                                  
        }
        items[count-1].n = front.n;
        r--;
    }

    while ( r < 0 )  // rotate negatively.
    {
        if ( i == top+1 )
        {
            front.n = items[top+1].n;  
            items[top+1].n = items[count-1].n; // switch last with first
        }

        back.n = items[++i].n; // second …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm

3
推荐指数
3
解决办法
3361
查看次数

如何在没有额外堆内存的情况下循环移位阵列?

如何编写一个函数shift(int* arr, int k)循环移位一个整数k的数组?我不能说堆中的"malloc"内存.

例如,使用伪代码,shift([1, 2, 3, 4], 2)返回[3, 4, 1, 2]shift([3, 1, 5, 5], 103)返回[1, 5, 5, 3].我已经尝试使用模数来实现这种效果,如这个Java程序所示,其中我基本上迭代了一半的数组和交换值.

public static int* shift(int* arr, int k) {
  int half_array_len = arr.length / 2;
  for (int i = 0; i < half_array_len; ++i) {
    // Swap!
    int newIndex = (i + k) % arr.length;
    int temp = arr[i];
    arr[i] = arr[newIndex];
    arr[newIndex] = arr[i];
  }
  return arr;
}
Run Code Online (Sandbox Code Playgroud)

但是,我相信这个功能仅适用于偶数长度的数组.

如何实现shift …

algorithm

3
推荐指数
1
解决办法
2779
查看次数

标签 统计

algorithm ×2

c++ ×1