38.Search a 2D Matrix II-搜索二维矩阵 II(中等题)

来源:互联网 发布:软件培训学校哪家好 编辑:程序博客网 时间:2024/05/22 08:26

翻转字符串

  1. 题目

    写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

    这个矩阵具有以下特性:
    每行中的整数从左到右是排序的。
    每一列的整数从上到下是排序的。
    在每一行或每一列中没有重复的整数。

  2. 样例

    考虑下列矩阵:
    这里写图片描述
    给出target = 3,返回 2

  3. 挑战

    要求O(m+n) 时间复杂度和O(1) 额外空间

  4. 题解

采用分治法的思想,从矩阵右上角开始遍历,
如果matrix[i][j]等于target,则所在行列就不用再查找了;
如果matrix[i][j]大于target,则所在列就不用再查找了;
如果matrix[i][j]小于target,则所在行就不用再查找了;

public class Solution {    /**     * @param matrix: A list of lists of integers     * @param: A number you want to search in the matrix     * @return: An integer indicate the occurrence of target in the given matrix     */    public int searchMatrix(int[][] matrix, int target) {        if (matrix.length == 0)        {            return 0;        }        int i = 0;        int j = matrix[0].length-1;        int count = 0;        while (i < matrix.length && j >= 0)        {            if (matrix[i][j] == target)            {                count++;                ++i;                --j;            }            else if (matrix[i][j] < target)            {                ++i;            }            else if (matrix[i][j] > target)            {                --j;            }        }        return count;    }}

Last Update 2016.9.26

0 0