输入数组长度 n 输入数组 a[1...n] 输入查找个数m 输入查找数字b[1...m] 输出 YES or NO 查找有则YES 否则NO 。

题目来源:https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa?tpId=40&tqId=21531&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

我的解法及归纳:

#include
#include

const int maxn=100;

using namespace std;

int main(){
int n,m;
scanf("%d",&n);
int a[maxn];
for(int i=0;i scanf("%d",&a[i]);
}
int b[maxn];
int j=0;
int i=0;
for(;j scanf("%d",&b[j]);
for(;i if(a[i]b[j]){
printf(“YES\n”);
break;
}
}
if(i
n) printf(“NO\n”);

}
 return 0;

}

错误点及改进:
1,时间复杂度过高,这里选择嵌套循环查找,复杂度较高,是o(n2),数据量太大容易崩溃,建议使用二分查找
2,变量i的作用域,与更新,变量j的上限m
逻辑混乱,细节没把控好

改进版本:
1,嵌套双重遍历
#include

const int maxn=100;

using namespace std;

int main(){
int n,m;
scanf("%d",&n);
int a[maxn];
for(int i=0;i scanf("%d",&a[i]);
}
int b;
scanf("%d", &m);
for(int j = 0;j scanf("%d",&b);
int i = 0;
for(;i if(a[i]b){
printf(“YES\n”);
break;
}
}
if(i
n) printf(“NO\n”);

}
 return 0;

}

2,改为二分查找
#include
#include
#include
using namespace std;
const int MAXN=100;
int arr[MAXN];
bool BinarySearch(int n,int target){
int left=0;
int right=n-1;
while(left<=right){
int middle=left+(right-left)/2;
if(arr[middle] left=middle+1;
}else if(target right=middle-1;
}else{
return true;
}
}
return false;
}
int main(){
int n,m;
while(scanf("%d",&n)!=EOF){
for(int i=0;i scanf("%d",&arr[i]);
}
sort(arr,arr+n);
scanf("%d",&m);
for(int i=0;i int target;
scanf("%d",&target);
if(BinarySearch(n,target)){
printf(“YES\n”);
}
else{
printf(“NO\n”);
}

    }
}

}

你可能感兴趣的:(刷题)