240. Search a 2D Matrix II

leetcode

Posted by chl on May 9, 2019

题目

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.

题意

给定一个矩阵,矩阵中每一行从左到右升序排序,每一列从上到下升序排序;寻找target值是否在矩阵中

题解

利用有序的特点,从右上角开始寻找
1)若右上角大于目标值,则范围去掉当前最后一列
2)若右上角小于目标值,则范围去掉当前第一行

代码

func searchMatrix(matrix [][]int, target int) bool {
    M := len(matrix)
    if M==0{
        return false
    }
    
    N := len(matrix[0])
    if N==0{
        return false
    }
    
    m := 0
    n := N-1
    
    for m<M&&n>=0{
        if matrix[m][n]==target{
            return true
        }
        
        if matrix[m][n]>target{
            n = n - 1
        }else{
            m = m + 1
        }
    }
    return false    
    
}

总结

因为剑指offer里面也做过,思路也比较简单,所以直接就做出来了。