码迷,mamicode.com
首页 > 其他好文 > 详细

240 Search a 2D Matrix II 搜索二维矩阵 II

时间:2018-04-09 15:51:25      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:script   targe   ems   bsp   des   算法   mat   return   矩阵   

编写一个高效的算法来搜索 m x n 矩阵中的一个目标值。该矩阵具有以下特性:
    每行的元素从左到右升序排列。
    每列的元素从上到下升序排列。
例如,
考虑下面的矩阵:
[
  [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。
详见:https://leetcode.com/problems/search-a-2d-matrix-ii/description/

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty()||matrix[0].empty())
        {
            return false;
        }
        int row=matrix.size();
        int col=matrix[0].size();
        int i=row-1;
        int j=0;
        while(i>=0&&j<col)
        {
            if(target>matrix[i][j])
            {
                ++j;
            }
            else if(target<matrix[i][j])
            {
                --i;
            }
            else
            {
                return true;
            }
        }
        return false;
    }
};

 

240 Search a 2D Matrix II 搜索二维矩阵 II

标签:script   targe   ems   bsp   des   算法   mat   return   矩阵   

原文地址:https://www.cnblogs.com/xidian2014/p/8760106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!