gpt4 book ai didi

c - Ubuntu 给我错误的输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:50:57 26 4
gpt4 key购买 nike

我面临一个非常不寻常的问题。这是我使用合并排序打印重复最大次数的数字的程序。

#include<stdio.h>
int n;
int merge(int a[],int low,int mid,int high){
int i=low,j=mid+1,c[n],k=low;
while((i<=mid) && (j<=high)){
if(a[i]<=a[j]){
c[k]=a[i];
i=i+1;
k=k+1;
}

else{
c[k]=a[j];
k=k+1;
j=j+1;
}
}

while(i<=mid){
c[k]=a[i];
i=i+1;
k=k+1;
}

while(j<=high){
c[k]=a[j];
j=j+1;
k=k+1;
}

for(i=low;i<=high;i++){
a[i]=c[i];
}
return 0;
}


int mergeSort(int a[],int low,int high){
int mid=0;
if(low<high){
mid=(low+high)/2;

mergeSort(a,low,mid);
mergeSort(a,mid+1,high);

merge(a,low,mid,high);
}
return 0;
}

int main(){
int i,a[n];
printf("\nEnter the size of array:\n");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
mergeSort(a,0,n-1);
printf("\nThe array after merge sort is-\n");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
i=0;
int j=i+1,count=1,maxCount=1,flag=0,f=0;
int arr1[n],arr2[n];
//printf("%d ",n);
while(i<(n-1) && j<n){
j=i+1;
while(a[i]==a[j]){
count++;
j++;
}
//printf("%d %d %d %d %d\n",count,a[i],a[j],i,j);
if(count>1 && count>=maxCount){
//printf("%d repeated %d times",a[i],count);
arr1[f]=count;
arr2[f]=a[i];
flag=1;
f++;
maxCount=count;
}
i=j;
count=1;
}
for(i=0;i<f;i++){
if(arr1[i]==maxCount)
printf("\n%d repeated %d times\n",arr2[i],arr1[i]);
}
if(flag==0){
printf("\nNo repetitions\n");
}
return 0;
}

When running this program on Ubuntu, I'm getting this output-

When running the exact same program on GeeksforGeeks IDE with the same inputs[But on hackerrank IDE for the same input I'm getting the right output.] 2 ,我得到了同样的错误输出-

请解释为什么同一个程序只能在 hackerrank IDE 上运行。是因为时间复杂度吗?根据我的说法,这是 nlogn 并且经过优化。还是因为空间复杂度?请解释。谢谢。

最佳答案

程序中至少有一个错误:

int i,a[n];
printf("\nEnter the size of array:\n");
scanf("%d",&n);

创建数组a时,尚未设置n

n(这是一个具有 extern 存储的变量)被初始化为零,因此您的数组大小将为零。由于您随后将项目放入其中,因此您将数据存储在其分配的空间之外,这是未定义的行为。任何事情都可能发生,并且在不同的平台上可能会有所不同。

关于c - Ubuntu 给我错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51872190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com