题解 | #查找#
查找
https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; int arr[100]; int binary_search(int x, int n) { //找到返回true int left = 0; int right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { //右边往左缩 right = mid - 1; //最后边界情况,right可能与left相等,下次right可能变成left-1 } else { left = mid + 1; } } return -1; } int main() { int n, m; while (scanf("%d", &n) != EOF) { for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } sort(arr, arr + n); scanf("%d", &m); for (int i = 0; i < m; i++) { int x; scanf("%d", &x); if (binary_search(x, n) != -1) { printf("YES\n"); } else { printf("NO\n"); } } } return 0; }