E : B DS二分查找_搜索二维矩阵

Description

使用二分查找法来判断m*n矩阵matrix中是否存在目标值target。

该矩阵有以下特性:

  1. 每行中的整数从左到右升序排列;
  2. 每行的第一个整数大于前一行的最后一个整数。

Input

第一行输入m和n,分别表示矩阵的行数和列数,接着输入m*n个整数。

接着,输入查找次数t,接着依次输入t个整数target。

Output

对于每次查找,若target存在于矩阵中,则输出true,否则输出false。

共输出t行。

Sample

#0

Input

cpp 复制代码
3 4
-1 3 5 7
10 11 16 20
23 30 34 60

3
3
13
16

Output

cpp 复制代码
true
false
true

Hint

1 <= m, n <= 100

-10^4 <= matrixij, target <= 10^4

AC代码

cpp 复制代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 101;
int matrix[N][N];
int target;

bool checkRow(int x)
{
	return matrix[x][0] > target;
}
bool check(int x, int row, bool& ret)
{
	if (matrix[row][x] == target)ret = true;
	return matrix[row][x] > target;
}
//target是要查找的值  m为行数,n为列数
bool MatrixBinarySearch( int m,int n)
{
	int l, r;
	bool ret = false;

	l = 0, r = m ;//先利用二分法判断target可能在哪一行中
	while (l < r)
	{
		int mid = l + r >> 1;
		if (checkRow(mid))r = mid;
		else l = mid +1;
	}

	int row = l-1;//将确定好的行保存

	l = 0, r = n ;
	while (l < r)//在确定可能存在target的行中二分查找
	{
		int mid = l + r >> 1;
		if (check(mid,row,ret))r = mid;
		else l = mid + 1;
	}

	return ret;
}


int main()
{
	int m, n;
	cin >> m >> n;
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++) {
			cin >> matrix[i][j];
		}
	}
	int t;
	cin >> t;
	while (t--)
	{
		cin >> target;
		bool ret = MatrixBinarySearch(  m, n);
		if (ret)cout << "true" << endl;
		else cout << "false" << endl;
	}
	return 0;
}
相关推荐
To_OC14 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
刘马想放假1 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
北域码匠2 天前
冒泡排序太慢?鸡尾酒排序双向优化,原生 C# 零第三方库完整代码
数据结构·排序算法·泛型·c# 算法·鸡尾酒排序·原生 c# 开发·冒泡排序优化·嵌入式算法