题解 | #查找#
查找
https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa
#include <iostream> #include "cstdio" #include "algorithm" using namespace std; bool BinarySearch(int arr[], int left, int right, int x) { int mid; while (left <= right) { mid = (left + right) / 2; if (arr[mid] == x) return true; if (arr[mid] > x) { right = mid - 1; } else left = mid + 1; } return false; } int main() { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } sort(arr, arr + n); ///二分查找需要有序数组 int m; scanf("%d", &m); int integer[m]; for (int i = 0; i < m; i++) { scanf("%d", integer + i); } for (int i = 0; i < m; i++) { if (BinarySearch(arr, 0, n - 1, integer[i])) printf("%s\n", "YES"); else printf("%s\n", "NO"); } return 0; }