Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

240. 搜索二维矩阵 II #27

Open
yankewei opened this issue Mar 21, 2020 · 0 comments
Open

240. 搜索二维矩阵 II #27

yankewei opened this issue Mar 21, 2020 · 0 comments
Labels
中等 题目难度为中等 二分查找 题目包含二分查找解法

Comments

@yankewei
Copy link
Owner

yankewei commented Mar 21, 2020

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

示例:

现有矩阵 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]
]

给定 target = 5,返回 true。
给定 target = 20,返回 false。

解答

暴力法

遍历即可

func searchMatrix(matrix [][]int, target int) bool {
    if len(matrix) == 0 {
        return false
    }
    row, column := len(matrix), len(matrix[0])
    for i :=0; i < row; i++ {
        for j := 0; j < column; j++ {
            if matrix[i][j] == target {
                return true
            }
        }
    }
    return false
}
从每行的尾部向前遍历
func searchMatrix(matrix [][]int, target int) bool {
    if len(matrix) == 0 {
        return false
    }
    row, column := len(matrix), len(matrix[0])
    i, j := 0, column
    for i < row && j > 0 {
        if matrix[i][j-1] == target {
            return true
        } else if matrix[i][j-1] < target {
            i++
        } else {
            j--
        }
    }
    return false
}
二分查找

二分查找看似简单,但是溢出和边界都有坑

func searchMatrix(matrix [][]int, target int) bool {
    if len(matrix) == 0 {
	return false
    }
    row, column := len(matrix), len(matrix[0])
    for i := 0; i < row; i++ {
	l, r := 0, column-1
        for l <= r {
            mid := (l + r) / 2
            if matrix[i][mid] == target {
	        return true
	    }
	    if matrix[i][mid] > target {
		r = mid - 1
	    } else {
		l = mid + 1
	    }
        }
    }
    return false
}
@yankewei yankewei added 中等 题目难度为中等 二分查找 题目包含二分查找解法 labels Mar 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 二分查找 题目包含二分查找解法
Projects
None yet
Development

No branches or pull requests

1 participant