Skip to content

Latest commit

 

History

History
99 lines (75 loc) · 1.98 KB

74.搜索二维矩阵.md

File metadata and controls

99 lines (75 loc) · 1.98 KB

74. 搜索二维矩阵

url

题目

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

方法

code

js

let searchMatrix = (matrix, target) => {
    if (matrix === null || matrix.length === 0 || matrix[0].length === 0) return false;
    let rows = matrix.length, cols = matrix[0].length;
    let c = cols - 1, r = 0;
    while (c >= 0 && r < rows) {
        if (matrix[r][c] === target)
            return true;
        else if (matrix[r][c] < target)
            r++;
        else
            c--;
    }
    return false
}

go

func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return false
	}
	rows, cols := len(matrix), len(matrix[0])
	c, r := cols - 1, 0
	for c >= 0 && r < rows {
		if matrix[r][c] == target {
			return true
		} else if matrix[r][c] < target {
			r++
		} else {
			c--
		}
	}
	return false
}

java

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return false;
        int rows = matrix.length, cols = matrix[0].length;
        int c = cols - 1, r = 0;
        while (c >= 0 && r < rows) {
            if (matrix[r][c] == target)
                return true;
            else if (matrix[r][c] < target)
                r++;
            else
                c--;
        }
        return false;
    }
}