题目:在一个二维数组中,每一行都是按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。例如下面的二维数组就是每行、每列递增排序。如果在这个数组中查找数字7,则返回true,如果查找数字5,由于数组不含有该数字,则返回false。
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
分析:因为该二维数组是从左到右以及从上到下的递增,所有我们可以先比较第一行最后最后一列的数字与查找的数字的大小。如果该数字等于要查找的数字,则查找结束;如果大于要查找的数字,则排除该数字所在的列;如果小于要查找的数字,则排除要查找的行。如果查找范围为空时,则证明该二维数组中不含有该数字。
实现代码:
/*
面试题目4:二位数组中的查找
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排列,
每一列都按照从上到下递增的顺序排列。请完成一个函数,输入这样的一个二维数组和一个整数,判断是否含有该整数
*/
/*
函数功能:判断二维数组中是否含有某个值
参数:
numbers:二维数组,
number_i:二维数组的行
number_j:二维数组的列
value:需要判定的值
返回值:
true:找到改值
false:未找到改值或者参数不合法
*/
bool selectNumber(int *numbers,int number_i,int number_j, int& value)
{
//合法性判断
if (numbers == nullptr || number_i <= 0 || number_j <= 0 )
{
std::cout << "数组不合法" << endl;
return false;
}
int temp_i = 0; //第一行
int temp_j = number_j-1; //最后一列
while (temp_i < number_i && temp_j >= 0)
{
cout << "i:" << temp_i << "j:" << temp_j << endl;
if (numbers[temp_i*number_j + temp_j] == value)
{
cout << "在二维数组中找到该值,位置为" <<endl;
cout << "i:" << temp_i << "j:" << temp_j << endl;
cout << value<<endl;
return true;
}
else if (numbers[temp_i*number_j + temp_j] < value)
{
++temp_i;
}
else
{
--temp_j;
}
}
return false;
}
完整测试代码:
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
using namespace std;
/*
面试题目4:二位数组中的查找
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排列,
每一列都按照从上到下递增的顺序排列。请完成一个函数,输入这样的一个二维数组和一个整数,判断是否含有该整数
*/
/*
函数功能:判断二维数组中是否含有某个值
参数:
numbers:二维数组,
number_i:二维数组的行
number_j:二维数组的列
value:需要判定的值
返回值:
true:找到改值
false:未找到改值或者参数不合法
*/
bool selectNumber(int *numbers,int number_i,int number_j, int& value)
{
//合法性判断
if (numbers == nullptr || number_i <= 0 || number_j <= 0 )
{
std::cout << "数组不合法" << endl;
return false;
}
int temp_i = 0; //第一行
int temp_j = number_j-1; //最后一列
while (temp_i < number_i && temp_j >= 0)
{
cout << "i:" << temp_i << "j:" << temp_j << endl;
if (numbers[temp_i*number_j + temp_j] == value)
{
cout << "在二维数组中找到该值,位置为" <<endl;
cout << "i:" << temp_i << "j:" << temp_j << endl;
cout << value<<endl;
return true;
}
else if (numbers[temp_i*number_j + temp_j] < value)
{
++temp_i;
}
else
{
--temp_j;
}
}
return false;
}
int main()
{
//int value = 15;
//int num[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };
int value = 11;
int num[][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} };
bool ret = selectNumber((int*)num, 4, 4, value);
if (ret)
{
cout << "找到了";
}
else
{
cout << "未找到";
}
return 0;
}