博客
关于我
问题 C: 查找
阅读量:733 次
发布时间:2019-03-21

本文共 1178 字,大约阅读时间需要 3 分钟。

问题 C: 查找

题目描述

输入数组长度 n
输入数组 a[1…n]
输入查找个数 m
输入查找数字 b[1…m]
输出 YES 或 NO 是否查找成功。

输入

输入有多组数据。
每组输入 n,然后输入 n 个整数,再输入 m,然后再输入 m 个整数(1 ≤ m ≤ n ≤ 100)。

输出

如果在数组中找到查找数字,输出 YES,否则输出 NO。

样例输入

6
3 2 5 4 7 8
2
3 6
样例输出
YES
NO

#include 
using namespace std;bool binarySearch(int a[], int left, int right, int ans) { int mid; while (left <= right) { mid = (left + right) / 2; if (a[mid] == ans) return true; else if (a[mid] > ans) right = mid - 1; else left = mid + 1; } return false;}int main() { int a[10001], b[10001], n, m, ans; while (scanf("%d", &n) != EOF) { for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a, a + n); cin >> m; for (int i = 0; i < m; ++i) { cin >> ans; if (binarySearch(a, 0, n - 1, ans)) { cout << "YES\n"; } else { cout << "NO\n"; } } } return 0;}

以上代码实现了一个简单的二分查找算法,适用于查找给定的目标值在一个已经排序好的数组中。程序首先读取输入数据,按照问题描述的要求进行处理并输出结果。代码中的 binarySearch 函数会返回目标值是否存在于数组中,如果存在则输出 "YES",否则输出 "NO"。

转载地址:http://mohgz.baihongyu.com/

你可能感兴趣的文章
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>