LeetCode -- Search a 2D Matrix II

原创 2015年11月21日 10:37:35
题目描述:
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,


Consider the following matrix:


[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
Given target = 5, return true.


Given target = 20, return false.


本题看起来是Search a 2D Matrix的扩展问题,其实和第一题的思路完全不一样。比较精简的思路是:
1.从左下开始找,如果matrix[r,c](r为行,c为列) < target,c++;否则r--。
2.直到r或c越界为止。




实现代码:


public class Solution {
    public bool SearchMatrix(int[,] matrix, int target) 
    {
        var rowLen = matrix.GetLength(0);
        var colLen = matrix.GetLength(1);
        
        var row = rowLen - 1;
        var col = 0;
        
        while(col <= colLen - 1 && row >= 0){
            if(matrix[row,col] == target){
                return true;
            }
            else if(matrix[row,col] < target){
                col ++;
            }
            else{
                row --;
            }
        }
        return false;
    }


}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode Search a 2D Matrix II

Description: Write an efficient algorithm that searches for a value in an m x n matrix. This ma...

LeetCode OJ 240. Search a 2D Matrix II

LeetCode OJ 240. Search a 2D Matrix IIDescriptionWrite an efficient algorithm that searches for a va...

Leetcode 240. Search a 2D Matrix II

这道题是同学问我的时候看到的,抱着solo的心态也做了一遍 第一次用的是二分和分治(刚好今晚老师也讲了分治) 然而效果好像不太佳? 先放一发题目: Write an efficient alg...

Java 实现leetcode Search a 2D Matrix II

Java 实现leetcode Search a 2D Matrix II本片依旧是关于Leetcode 里面算法题目的详解,实现Search a 2D Matrix II问题算法 问题描述:在这个...

Leetcode Search a 2D Matrix II

**题目:**Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has th...

LeetCode[240] Search a 2D Matrix II(动画演示)

目录目录 Problem Example Thought1 Thought2 Presentation 总结 Online Judge Search a 2D Matrix IIProblem: ...

[leetcode] 240 Search a 2D Matrix II

很经典的一道题,每行由左到右,每列由上到下升序排列,让我们采用高效的算法判断一个值是不是存在。 第一种方案:遍历行,若发现行首的元素 这个算法的最坏时间复杂度是O(n*logm)。当然如果你对行也...
  • NK_test
  • NK_test
  • 2015年08月19日 12:15
  • 962

<LeetCode OJ> 74. / 240. Search a 2D Matrix (I / II)

240. Search a 2D Matrix II My Submissions Question Total Accepted: 28527 Total Submissions: 8556...

Leetcode 240. Search a 2D Matrix II[medium]

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

LeetCode No.240 Search a 2D Matrix II

LeetCode No.240 Search a 2D Matrix II
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode -- Search a 2D Matrix II
举报原因:
原因补充:

(最多只允许输入30个字)