[Leetcode 74, medium] Search a 2D Matrix
来源:互联网 发布:淘宝排行查询 编辑:程序博客网 时间:2024/05/20 14:20
Problem:
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
.
Analysis:
Solutions:
C++:
bool searchMatrix(vector<vector<int> > &matrix, int target) { if(matrix.empty() || matrix[0].empty() || target < matrix[0][0] || target > matrix[matrix.size() - 1][matrix[0].size() - 1]) return false; int start = 0, end = matrix.size() - 1; for(; start <= end;) { if(start == end) break; else if(start == end - 1) { if(matrix[end][0] <= target) start = end; break; } else { int mid = (start + end) / 2; if(matrix[mid][0] == target) return true; else if(matrix[mid][0] < target) start = mid; else end = mid; } } int row = start; start = 0; end = matrix[row].size() - 1; for(; start <= end;) { if(start == end) { if(matrix[row][start] == target) return true; else return false; } else if(start == end - 1) { if(matrix[row][start] == target || matrix[row][end] == target) return true; else break; } else { int mid = (start + end) / 2; if(matrix[row][mid] == target) return true; else if(matrix[row][mid] < target) start = mid; else end = mid; } } return false; }Java:
Python:
0 0
- [Leetcode 74, medium] Search a 2D Matrix
- LeetCode-74-Search a 2D Matrix(二分查找)-Medium
- [Leetcode 240, Medium] Search a 2D Matrix II
- 【LeetCode】7(4)Search a 2D Matrix(Medium)
- 【LeetCode】(240)Search a 2D Matrix II(Medium)
- Leetcode 74. Search a 2D Matrix (Medium) (cpp)
- Leetcode 240. Search a 2D Matrix II (Medium) (cpp)
- 【LeetCode】240. Search a 2D Matrix II (Medium)
- Leetcode 240. Search a 2D Matrix II[medium]
- Search a 2D Matrix(medium)
- Medium:Search a 2D Matrix II
- Medium 74题 Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- LeetCode 74 Search a 2D Matrix
- [leetcode 74] Search a 2D Matrix
- [LeetCode 74]Search a 2D Matrix
- leetcode || 74、Search a 2D Matrix
- [LeetCode] Length of Last Word
- 实用的js
- 第二十题
- Google Protocol Buffer(1)—Overview
- ZeptoLab Code Rush 2015---C. Om Nom and Candies
- [Leetcode 74, medium] Search a 2D Matrix
- 关于java赋值的新手的一个小误区
- MINA 快速入门
- 第24课时,实践2,油量监控
- TowORthRee
- phpmyadmin,解决Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in t
- Unix网络编程(六)高级I/O技术之复用技术 select
- 动态规划之矩阵连乘
- 使用UIViewController自定义UITabBarController