【LeetCode】C# 74、Search a 2D Matrix

来源:互联网 发布:淘宝店铺分类导航 编辑:程序博客网 时间:2024/06/08 05:39

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.

在二维矩阵中找值。

思路一:转化为一维数组后二分法求值。

public class Solution {    public bool SearchMatrix(int[,] matrix, int target) {        if (matrix.Length == 0) return false;        if (matrix.Length == 1) return matrix[0, 0] == target;        int[] temp = new int[matrix.Length];        int m = 0;        foreach (int item in matrix)            temp[m++] = item;        int right = temp.Length-1;        int left = 0;        int mid;        while (left <= right)        {            mid = (left + right) / 2;            if (temp[mid] == target) return true;            else if (temp[mid] > target)                right = mid-1;            else                left = mid+1;        }        return false;    }}

思路二:先第一列二分法求值后改行二分法求值。

public class Solution {    public bool SearchMatrix(int[,] matrix, int target) {        if(matrix.Length==0) return false;        int m = matrix.GetLength(0),n=matrix.Length/m;        int u=0,l=0,d=m-1,r=n-1,mid;        mid = (u+d)/2;        while (d>u) {            mid = (u+d)/2;            if(matrix[mid,0]==target) return true;            else if(matrix[mid,0]>target) d = mid-1;            else u = mid+1;        }        if(u!=0 && matrix[u,0]>target) u--;        while (l<=r){            mid = (l+r)/2;            if(matrix[u,mid]==target) return true;            else if(matrix[u,mid]>target) r = mid-1;            else l = mid+1;        }        return false;    }}

思路三:先找行再找列。

public class Solution {    public bool SearchMatrix(int[,] matrix, int target) {        if(matrix.Length==0) return false;        int i = 0, m = matrix.GetLength(0),n=matrix.Length/m,j=n-1;        while (i < m && j >= 0) {            if (matrix[i,j] == target) {                return true;            } else if (matrix[i,j] > target) {                j--;            } else {                i++;            }        }          return false;    }}