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