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
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- Wampserver图标黄色解决
- ELF文件格式与程序的编译链接
- 早期(编译器)优化
- 单向链表的建立
- 使用myEclipse来生成hibernate 持久化类和映射文件
- leetcode--Search a 2D Matrix
- STL数字字符串转换为数字
- linux中./a.out > outfile 2>&1和./a.out 2> &1 >outfile重定问题的理解
- SSH——Hibernate初学者之旅(六)
- Python使用Requests第三方库自动登陆知乎
- 直升机飞行控制
- Android JellyBean Keyguard锁屏
- LeetCode(17)-Letter Combinations of a Phone Number
- android PopupWindow详解