前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode74. 搜索二维矩阵&240. 搜索二维矩阵 II

LeetCode74. 搜索二维矩阵&240. 搜索二维矩阵 II

作者头像
mathor
发布2018-08-17 15:51:04
1.2K0
发布2018-08-17 15:51:04
举报
文章被收录于专栏:mathormathor
题目链接:LeetCode74

 通常情况下在一个矩阵中搜索一个元素时间复杂度是O(m*n)的,但是在这里只用O(m+n)的时间复杂度就能完成,说一下思路  以右上角为起点,如果当前的值小于我要寻找的值,就往下移动,如果当前的值大于我要寻找的值,就往左移动

代码语言:javascript
复制
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0)
            return false;
        int m = matrix.length;
        int n = matrix[0].length;
        int i = 0,j = n - 1;
        while(i < m && j >= 0) {
            if(matrix[i][j] == target) 
                return true;
            else if(matrix[i][j] > target)
                --j;
            else 
                ++i;
        }
        return false;
    }
}
题目链接:LeetCode240
代码语言:javascript
复制
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length == 0)
            return false;
        int m = matrix.length;
        int n = matrix[0].length;
        int i = 0,j = n - 1;
        while(i < m && j >= 0) {
            if(matrix[i][j] == target) 
                return true;
            else if(matrix[i][j] > target)
                --j;
            else 
                ++i;
        }
        return false;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接:LeetCode74
  • 题目链接:LeetCode240
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档