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

Search a 2D Matrix_LeetCode

时间:2017-12-11 23:07:19      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:style   example   search   hat   ast   sid   方法   row   get   

Description:

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.

 

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

 

解题思路:

 

方法一:

最普通的二维数组用两层循环遍历的方法。但是复杂度有O(m*n),非常高,代码如下:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        //int flag = 0;
        if(matrix.empty()||matrix[0].empty()) return false;
        int m = matrix.size();
        int n = matrix[0].size();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == target) {
                    return true;
                }
            }
        }
        return false;
    }
};

 

方法二:

从右上角开始遍历,根据这个二维数组的特殊排列性质,可以通过大小比较,选择向左或者向下,复杂度有所减少,为O(m),代码如下:

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

 

Search a 2D Matrix_LeetCode

标签:style   example   search   hat   ast   sid   方法   row   get   

原文地址:http://www.cnblogs.com/SYSU-Bango/p/8025287.html

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