Google/LintCode:M-搜索二维矩阵 II

49 篇文章 0 订阅
4 篇文章 0 订阅

题目


题目来源:Link


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

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每一列的整数从上到下是排序的。
  • 在每一行或每一列中没有重复的整数。

样例

考虑下列矩阵:

[

    [1, 3, 5, 7],

    [2, 4, 7, 8],

    [3, 5, 9, 10]

]

给出target = 3,返回 2

挑战 

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


分析


(1)最暴力方法,遍历,TC=O(m*n)

(2)小优化,遍历行或者列,二分查找

(3)最优化,利用题目中数字行列特点,行列可以组合成顺序序列,TC=O(m+n)


代码


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) {
        // write your code here
        if(matrix==null || matrix.length==0) return 0;
        
        int m = matrix.length;
        int n = matrix[0].length;
        
        //从左下角开始,列与行拼接,正好是一个递增数列
        int i=m-1;
        int j=0;
        int count=0;
        while(i>=0 && j<=n-1){
            if(target<matrix[i][j]){
                i--;
            }else if(target==matrix[i][j]){
                i--;
                j++;
                count++;
            }else{
                j++;
            }
        }
        return count;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值