判斷二維數組是否包含某數
題目
已知一個整數型二維數組,行和列的數值都是遞增的。現在給定數值'x',判斷二維數組是否包含'x'。
方法
假設二維數組如下圖排列,取二維數組右上角數值和'x'比較:(1) 如果比'x'大,則這一列就剔除;(2) 如果比'x'小,則這一行就剔除。
代碼
#include <vector>
#include <stdio.h>
using namespace std;
int raws = 3;
int cols = 4;
bool find(int target, int array[][4]);
int main(int argc, char *argv[])
{
int target = 4;
int array[][4] = {{1, 3, 5, 6},{3, 4, 7, 8},{4, 5, 8, 9}};
int result = find(target, array);
printf("result is :%d ",result);
return result;
}
bool find(int target, int array[][4])
{
if(raws > 0 && cols > 0)
{
int raw = 0;
int col = cols - 1;
while((raw != raws) && (col >= 0))
{
if(array[raw][col] == target)
return true;
if(array[raw][col] > target)
col--;
if(array[raw][col] < target)
raw++;
}
}
return false;
}