Leetcode---剑指Offer题4---二维数组中的查找 1、介绍 2、题解
剑指Offer-面试题4---二维数组中的查找
https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/submissions/
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
2、题解
1.我的写法:
从二维数组左下角开始比较。如果小于目标数则行数++;如果大于目标数则列数--。
时间复杂度:O(行高 + 列宽)
C#实现
public bool FindNumberIn2DArray(int[][] matrix, int target)
{
//高和宽
int vLen = matrix.Length;
int hLen = matrix[0].Length;
if (matrix == null || vLen < 1 || hLen < 1)
return false;
int vStart = matrix.Length-1;
int hStart = 0;
while (vStart>=0 && hStart<hLen)
{
if (matrix[vStart][hStart] > target)
{
vStart--;
}
else if (matrix[vStart][hStart] < target)
{
hStart++;
}
else
{
return true;
}
}
return false;
}
Lua实现
myArray = {}
for i=1,2,1 do
myArray[i] = {}
end
--自定义的一个二维数组(2行3列)
local temp = 1
for i=1,2,1 do
for j=1,3,1 do
myArray[i][j] = temp
temp = temp + 1
end
end
function SearchNumber(arr,targetNum)
local row = #arr
local column = #arr[1]
local i = 1
local j = column
--从右上角开始比较
while(i<=row and j>=1) do
if(arr[i][j] > targetNum) then
j = j-1
elseif(arr[i][j] < targetNum) then
i = i+1
else
return true
end
end
return false
end
local isFind = SearchNumber(myArray,7)
if find==nil then
print('未找到目标数字')
else
print('找到目标数字')
end