Day5
This commit is contained in:
11
74. Search a 2D Matrix/74. Search a 2D Matrix.csproj
Normal file
11
74. Search a 2D Matrix/74. Search a 2D Matrix.csproj
Normal file
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_74._Search_a_2D_Matrix</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
11
74. Search a 2D Matrix/Program.cs
Normal file
11
74. Search a 2D Matrix/Program.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace _74._Search_a_2D_Matrix
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
int[][] matrix = new int[][] { new int[] { 1 }};
|
||||
Console.WriteLine(new Solution().SearchMatrix(matrix, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
30
74. Search a 2D Matrix/Solution.cs
Normal file
30
74. Search a 2D Matrix/Solution.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
namespace _74._Search_a_2D_Matrix;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public bool SearchMatrix(int[][] matrix, int target)
|
||||
{
|
||||
int row = SearchInsert((i) => matrix[i][0], matrix.Length, target);
|
||||
if (row < matrix.Length && matrix[row][0] == target)
|
||||
return true;
|
||||
if (row > 0)
|
||||
row--;
|
||||
int column = SearchInsert((i) => matrix[row][i], matrix[row].Length, target);
|
||||
return column < matrix[row].Length && matrix[row][column] == target;
|
||||
}
|
||||
|
||||
private int SearchInsert(Func<int, int> getByIndex, int len, int target)
|
||||
{
|
||||
int l = -1;
|
||||
int r = len;
|
||||
while (l != r - 1)
|
||||
{
|
||||
int i = (r + l) / 2;
|
||||
if (getByIndex(i) >= target)
|
||||
r = i;
|
||||
else
|
||||
l = i;
|
||||
}
|
||||
return l + 1;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user