使用二分查找或者map进行快速查找
查找
http://www.nowcoder.com/questionTerminal/d93db01c2ee44e8a9237d63842aca8aa
使用map时间复杂度为O(m)
#include <iostream> #include <map> using namespace std; int main() { int n; int m; while(cin>>n) { map<int,bool> mp; for (int i = 0; i < n; i++) { int temp; cin>>temp; mp[temp] = true; } cin>>m; for (int i = 0; i < m; i++) { int temp; cin>>temp; if (mp.find(temp) != mp.end()) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } } }
使用二分查找时间复杂度为O(mlogn)
#include <iostream> #include <algorithm> using namespace std; int main() { int n; int m; while(cin>>n) { int *arr = new int[n]; for (int i = 0; i < n; i++) { cin>>arr[i]; } sort(arr, arr+n); cin>>m; int *test = new int[m]; for (int i = 0; i < m; i++) { cin>>test[i]; if (binary_search(arr, arr + n, test[i])) { cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } } }