c++ - 反转数组而不改变零的位置

标签 c++ arrays algorithm data-structures

我刚刚和我的 friend 一起尝试了一些数据结构问题。我从一位 friend 那里遇到了这个问题,他也无法解决。

Question: Reverse an array without changing position of zeroes. example : if array has has 0 5 7 8 0 9 then the result should be 0 9 8 7 0 5.

我尝试过,但它在所有情况下都不能正确执行,如果代码看起来很难看,我很抱歉我现在是新手。

#include<iostream>
using namespace std;
int main()
{
    int arr[100], tot, i, j, temp;
    cout<<"Enter the Size for Array: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    cout<<"\nThe Original Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    j = tot-1;
    for(i=0; i<j; i++, j--)
    {
        if(arr[i] == 0) {
            i++;
            continue;
        }else if(arr[j] == 0) {
           j--;
           continue;
        }
        else {
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    cout<<"\n\nThe Reverse of Given Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}

我已经尝试了上面的代码,但它没有给出正确的结果。

最佳答案

这里的问题是,您在循环的每次迭代中都修改了循环变量 ij;仅当元素被交换时才需要更新:

for(i=0; i<j;)
{
    if(arr[i] == 0) {
        i++;
    }else if(arr[j] == 0) {
       j--;
    }
    else {
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        ++i;
        --j;
    }
}

Demo on godbolt.org

关于c++ - 反转数组而不改变零的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74873752/

相关文章:

c++ - char数组的正确输入法?

c++ - 如何使用索引访问 C++ 结构属性值?

javascript - 对数组中的每个 10 重复操作

c - Switch case 弄乱了我试图转换的数组

Python/Numpy 查找长度变量跨度

python - 以中间元素为轴心进行快速排序

c++ - C++11 是否使用移动语义来进行复制到分配优化?

c++ - 从 unsigned char 数组转换为 double

具有超过 4gb 元素的 Java 数组

c# - 基于 Kinect 数据的 HMM 3D 手势识别特征提取