Search 2D matrix

来源:互联网 发布:js 时分秒 时间选择器 编辑:程序博客网 时间:2024/05/17 09:22

Search 2D matrix

在矩阵中搜索目标数字。

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.

Example

Consider the following matrix:

[

    [1, 3, 5, 7],

    [10, 11, 16, 20],

    [23, 30, 34, 50]

]

Given target = 3, return true.

Solution:

右上角搜索:

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

多行二分搜索:

public boolean searchMatrix(int[][] matrix, int target) {    if(matrix == null || matrix.length == 0) {        return false;    }    int row = matrix.length - 1;    int col = matrix[0].length - 1;    for(int i = 0; i <= row; i++) {        if(matrix[i][0] <= target && target <= matrix[i][col]) {            if(bs(matrix[i], target)) {                return true;            }        }    }    return false;}    private boolean bs(int[] nums, int target) {    int start = 0;    int end = nums.length - 1;    int mid;    while (start + 1 < end) { <span style="white-space:pre"></span>mid = (start + ((end - start) >> 1));<span style="white-space:pre"></span>if (target < nums[mid]) {<span style="white-space:pre"></span>end = mid - 1;<span style="white-space:pre"></span>} else if (target > nums[mid]) {<span style="white-space:pre"></span>start = mid + 1;<span style="white-space:pre"></span>} else {<span style="white-space:pre"></span>start = mid;<span style="white-space:pre"></span>}    }    if (nums[end] == target) {<span style="white-space:pre"></span>return true;    } else if (nums[start] == target) {<span style="white-space:pre"></span>return true;    } else {<span style="white-space:pre"></span>return false;    }}

思路:

一次遍历,右上角出发向左下角前进。

1. 一行末尾为本行最大值

2. 同一列,下一行比本行的值大

多行二分搜索,循环外要有return。只搜索可能含有目标数字的行。

0 0
原创粉丝点击