剑指offer——4.二维数组中的查找

题目:

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

知识点:

  1. 创建二维数组(居然忘了!)

注意:

  1. 写代码之前,先将输入的范围固定

代码实现(java):

  • 先将要查找数字num与数组右上的数字进行比较,大于则删除列,小于则删除行,等于输出true
/**
	 * 先将要查找数字num与数组右上的数字进行比较,大于则删除列,小于则删除行,等于输出true
	 * @param arrs
	 * @param num
	 * @return
	 */
	private static boolean findNum(int[][] arrs, int num) {
		if(arrs!=null) {
			//判断右上方的数是否与查找数相等
			int rowNums = arrs[0].length;
			int columnIndex = arrs.length-1;
			int rowIndex = 0;
			while(rowIndex<=rowNums-1 && columnIndex>=0) {
				if(num == arrs[rowIndex][columnIndex]) {
					return true;
				}else if(num < arrs[rowIndex][columnIndex]) {
					columnIndex--;
				}else {
					rowIndex++;
				}
			}
			//若大于,则删除整列,继续判断;
			//若小于,则删除整行,继续判断;直至等于查找的数
			return false;
		}else {
			return false;
		}
		
	}

 代码实现(c++):

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

bool Find(vector<vector<int> > array, int target)
{
	bool found = false;
	int row = 0;
	int col = array[0].size() - 1;
	//循环至row大于array[0].size()-1或col小于0
	while (row <= array[0].size()-1 && col >= 0)
	{
		//比较target与右上角数的大小
		if (array[row][col] == target)
		{
			found = true;
			break;
		}
		else if (array[row][col] < target)
		{
			row++;
		}
		else
		{
			col--;
		}
	}
	return found;
}
int main()
{
	vector< vector<int> > vec(2, vector<int>(4));
	//赋值
	int a[2][4] = { { 1, 2, 8, 9 },{ 4, 7, 10, 13 } };
	
	for (int i = 0; i < 2; i++) {
		for (int j = 0; j < 4; j++) {
			vec[i][j] = a[i][j];
		}
	}
	//打印
	int m, n;
	for (m = 0; m < vec.size(); m++)
	{
		for (n = 0; n < vec[0].size(); n++)
		{
			cout << vec[m][n] << " ";
		}
		cout << endl;
	}
	bool isTrue = false;
	cout << isTrue << endl;
	isTrue = Find(vec, 7);
	cout << isTrue << endl;
	getchar();

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值