leetcode--Search a 2D Matrix

来源:互联网 发布:aris软件流程 编辑:程序博客网 时间:2024/06/14 22:47

题目要求:https://leetcode.com/problems/search-a-2d-matrix/

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.

解题思路:这是在一个二位数组中查找数字的算法。而且这个数组是行有序的。因此思路在于从第一行开始将target和每行的最后一个元素进行比较,有三种情况:

1)刚好相等,返回true,

2)大于,则转到下一行继续进行比较,

3)小于,则转到这一行的前一列进行比较。


这一题虽然不难,但是我在写的过程中遇到了一个之前从没注意过的问题,那就是for(;;)循坏的双判断条件问题。对于下面三个语句,是否有区别呢?

1.

2.

3.


答案是肯定的。一直以来我都以为都是一样的,但是当我使用第一个for进行判断时,发现出错,但是改为第一个或者第三个就AC了,原因在于第二个表达式涉及到了逗号运算符的问题,相当于i < cow,j >=0这两个条件中,只满足了第二个,这是逗号运算符的性质。当然还有一种说法是i < cow,j >=0 相当于“或”的关系。个人比较偏向于第一种解释。至于逗号运算符的解释,见http://blog.csdn.net/wang37921/article/details/7530978

源代码:

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



0 0
原创粉丝点击