【leetCode】Search a 2D Matrix
来源:互联网 发布:中国网络的发展历程 编辑:程序博客网 时间:2024/06/05 20:44
题目:
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
.
中文大意:
写一个高效查找算法在一个m*n的矩阵中查找指定值。这个m*n矩阵拥有以下两个性质:
1、对于每一行,整数都是从左到右递增;
2、对于每一列,整数都是从低到高递增;
举个栗子:对于下面这个矩阵
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
思路:
对每一行进行二分查找.......
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { for(int i = 0; i < matrix.size();i++) { int colSize = matrix[i].size(); //如果这个数大于该行的最小值,小于该行的最大值 if(matrix[i][0]<= target && matrix[i][colSize-1]>=target) { bool j = binaySearch(matrix[i],target); if(j) return j; } } return false; }private:/*二分查找算法*/ bool binaySearch(vector<int> a,int target) { int length = a.size(); int left = 0, right = length - 1; int mid = (left + right) / 2;//(0+3)/2 == 1 while (left < right) { mid = (left + right) / 2; if (a[left] == target) return true; if (a[right] == target) return true; if (a[mid] == target) return true; else if (a[mid] < target) { left = mid + 1; continue; } else if (a[mid]>target) { right = mid; continue; } } if (left == right && a[left] == target) { return true; } else 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
- 能为父母做的事
- 单链表创建及其插入,删除,逆序
- centos下安装memcached
- java webservice实例教程
- hdu 4355 Party All the Time 典型三分
- 【leetCode】Search a 2D Matrix
- [Web3.0]什么是Web3.0/时代
- Hdu 4609 FFT
- 计票统计
- HDU 3452 Bonsai(最小割)
- Hibernate学习(7)关系映射
- 黑马程序员——java中面向对象基础
- Steps
- Java 基础