我有一项家庭作业任务是检查反向数组是否与使用函数的原始数组相同。我曾尝试编写代码,但每次运行它时它都会给我相同的“TAIP”答案。我阅读了如何反转数组的教程,所以我尝试使用 2 个数组:原始数组和反转数组,然后比较它。但是,它在我的代码中不起作用,我不知道为什么。
#include <iostream>
#include <fstream>
using namespace std;
void funk(int a[], int n, int b[], int &nes);
int main()
{
int a[10], n, b[10],nes = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
b[i] = a[i];//the same elements
}
funk(a, n, b, nes);
if (nes != 0) {
cout << "NE";
}
else
cout << "TAIP";
}
void funk(int a[], int n, int b[], int &nes) {
int j, i=0, pap;
j = i - 1; //last element
while (i < j)
{
pap = b[i];
b[i] = b[j];
b[j] = pap;
i++;
j--;
}
for (int c = 0; c < n; c++) {
if (a[c] != b[c]) {
nes++;
break;
}
}
}
输入:
6
8 5 8 1 3 8
我需要得到的输出:NE
最佳答案
您的方法似乎不必要地复杂且效率低下。对于n
元素的反向不变数组a
,条件a[i]==a[n-i-1]<对于
必须为 0
和 n/2
之间的所有 i
,true
。
示例性解决方案:
template <typename T>
bool is_reverse_invariant(T a[], size_t n)
{
for (size_t i = 0; i < n/2; i++)
if (a[i] != a[n-i-1]) return false;
return true;
}
你的代码有问题
int j, i=0, pap;
j = i - 1; //last element
是 j
应该初始化为
j = n - 1;
相反。
关于c++ - 检查反转数组是否与原始数组相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975792/