70,022
社区成员




#include<stdio.h>
#include<string.h>
int main(){
int n,i,k,r;
char str[]="NO";
scanf("%d",&n);
int a[n*n];
for(i=0;i<=(n*n-1);i++)
scanf("%d",&a[i]);
for(i=0;i<=(n*n-2);i++){
for(k=i+1;k<=(n*n-1);k++)
if(a[i]==a[k]){
strcpy(str,"YES");
break;}
if(str=="YES")
break;}
printf("%s",str);
return 0;}
检验矩阵重复元素
题目描述:编写程序判断任意给定n*n的两维整型数组中是否有相同元素。
输入:第一行输入数组行数n(≤10),第二行随机输入n*n个整数作为数组元素值。
输出:如果数组中有相同元素,则输出YES;否则,输出NO。
在你的代码中,可能会因为输入规模较大时,算法的时间复杂度较高而导致超时。你的代码是通过双重循环来比较数组元素是否相同的,这样的时间复杂度是O(n^2),在数组规模较大时可能会导致程序运行时间过长。
为了提高效率,你可以考虑使用一些更高效的算法。一个更快速的方法是使用哈希表(Hash Table)来记录已经出现过的元素,这样可以在O(1)的时间内判断元素是否重复。下面是一个使用哈希表的示例代码:
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
int main() {
int n;
scanf("%d", &n);
int a[MAX_SIZE * MAX_SIZE];
for (int i = 0; i < n * n; i++)
scanf("%d", &a[i]);
bool isDuplicate = false;
bool hashTable[MAX_SIZE * MAX_SIZE] = {false};
for (int i = 0; i < n * n; i++) {
if (hashTable[a[i]]) {
isDuplicate = true;
break;
}
hashTable[a[i]] = true;
}
printf("%s", isDuplicate ? "YES" : "NO");
return 0;
}
这个代码使用一个大小为 MAX_SIZE * MAX_SIZE 的布尔数组作为哈希表,初始化为 false。然后遍历数组,对于每个元素,检查对应哈希表位置的值是否为 true,如果是,说明元素重复,直接输出 "YES"。这样的算法时间复杂度为 O(n^2),适用于较大的输入规模。