所有代码均通过G++编译器测试,仅为练手纪录。
//面试题3:二维数组中的查找
//题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排列。
// 请完成一个函数,输入这样的一个二位数组和一个整数,判断数组中是否含有该整数。
//面试题3:二维数组中的查找
//题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排列。
// 请完成一个函数,输入这样的一个二位数组和一个整数,判断数组中是否含有该整数。
bool FindItem(int *array,int nRow,int nCol,int nItem)
{
if(NULL == array || nRow <= 0 || nCol <= 0)
{
return false;
}
int nCountRow = 0;
int nCountCol = nCol - 1;
while(nCountRow <= nRow && nCountCol >= 0)
{
int nPos = nCountRow * nCol + nCountCol;
if(array[nPos] == nItem)
{
LogInfo("%s,row:%d,col:%d",__FUNCTION__,nCountRow,nCountCol);
return true;
}
else if(array[nPos] > nItem)
{
--nCountCol;
}
else
{
++nCountRow;
}
}
return false;
}
void TestFindItem()
{
int array[3*3] = {1,2,8,2,4,9,4,7,10};
bool bFind = FindItem(array,3,3,4);
LogInfo("bFind:%d",bFind);
}
ZhaiPillary
2016-12-22