连续二维排序数组中数的查找

一维有序数按照二维存储的情况

题目描述
在一个二维数组中(每个一维数组的长度相同),第一行都按照从左到右递增的顺序排序,下一列按照从左到右递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

例如:数组中查找7是否存在?

  {1,  2,  3},
  {4,  5,  6},
  {7,  8,  9}

关于有序序列查找第一反应看是否可以用二分查找解决,由于二维数组从第一行到下面各行都是默认顺序递增有序,则直接二分查找,讲以为数组折成二维数组,难点是实现数组索引的转换即可。

#include <iostream>
#include <vector>
#include <string.h>
#include <map>
using namespace std;
class Solution {
public:
	int m, n;
	struct Node {
		int x;
		int y;
		Node(int x, int y) :x(x), y(y) {}
	};
	Node getIndex(Node node, int flag)
	{
		if (flag == 1)
		{
			if (node.y < m)
				node.y += 1;
			else
			{
				node.x += 1;
				node.y = 0;
			}
		}
		else
		{
			if (node.y > 0)
				node.y -= 1;
			else
			{
				node.x -= 1;
				node.y = n;
			}
		}
		return node;
	}
	bool Find(int target, vector<vector<int> > array) {
		m = array.size() - 1; 
		n = array[0].size() - 1;
		Node s(0, 0), e(m, n); // left
		while (s.x < e.x && s.y < e.y)
		{
			int x = (s.x + e.x) / 2;
			int y = (s.y + e.y) / 2;
			Node mid(x, y);
			if (array[mid.x][mid.y] < target)
				s = getIndex(s, 1);
			else if (array[mid.x][mid.y] > target)
				e = getIndex(e, -1);
			else
				return true;
		}
		return false;
	}
};

牛客网题目

题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

class Solution {
public:
	bool Find(int target, vector<vector<int> > array) {
		int m = array.size() - 1; 
		int n = array[0].size() - 1;
		for (int i = 0; i <= m; i++)
		{
			int l = 0, r = n;
			while (l <= r)
			{
				int mid = (l + r) / 2;
				if (array[i][mid] > target)
					r = mid - 1;
				else if (array[i][mid] < target)
					l = mid + 1;
				else
					return true;
			}
		}
		return false;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值