Exist or not please help

this is also showing tle…

sort the vector that you are making and then apply binary search for finding element
it reduces time complexity of your code.

Reference Code:

1 Like

ohh yess…it will decrease the complexity from O(NLOGN) to O(LOGN)

#include <bits/stdc++.h>
#include
using namespace std;

int main()
{
int x;
cin >> x;
while (x–)
{
int n;
cin >> n;
vector v;
for (int i = 0; i < n; i++)
{
int no;
cin >> no;
v.push_back(no);
}
sort(v.begin(),v.end());
int t, key;
cin >> t;
while(t–)
{
cin >> key;
int flag = 0;
int i=0;
while(i<n){
if(v[i]==key){
cout<<“Yes”<<endl;
break;
}
else if(v[i]>key){
flag = 1;
break;
}
else{
i++;
}
}
if(flag==1){
cout<<“No”<<endl;
}

    }
}

return 0;

}
still showing wrong

you have not use binary search correctly…
use Binary search correctly as :

#include<bits/stdc++.h>
using namespace std;
#define int long long int
bool find(int arr[],int n,int no){
	int s = 0, e = n-1;
	while(s<=e){
		int mid = (e-s)/2 +s;
		if(arr[mid]==no)
			return true;
		else if(arr[mid]>no){
			e = mid -1;
		}else
			s = mid + 1;
	}
	return false;
}
int32_t main() {
	int t;cin>>t;
	while(t--){
		int n;cin>>n;
		int arr[100000];
		for(int i=0;i<n;i++){
			cin>>arr[i];
		}
		sort(arr,arr+n);
		int q;cin>>q;
		for(int i=0;i<q;i++){
			int x;cin>>x;
			if(find(arr,n,x)==true){
				cout<<"Yes"<<endl;
			}else{
				cout<<"No"<<endl;
			}
		}
	}
	return 0;
}