Search a 2D Matrix II
来源:互联网 发布:软件项目管理ppt 编辑:程序博客网 时间:2024/05/29 09:43
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
解:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m,n; m=matrix.size(); if(m==0)return false; n=matrix[0].size(); int i=0; int l=0,r=n-1; while(i<m&&l<=r) { vector<int>& arr=matrix[i]; //这里注意用二分搜索一个lower bound的时候对要搜索的区间进行单向收缩,因此需要注意1. 只剩两个元素时为了使区间正确收缩到只剩一个元素,需要用对中点mid取上界(ceil函数)2. 只剩一个元素的时候退出循环,因此要额外检测最初给出的数列是不是只包含一个元素,进行元素大小的检测 while(l<r) { int mid_index=ceil((l+r)/2.); int mid=arr[mid_index]; if(mid==target)return true; else if(mid>target)r=mid_index-1; else l=mid_index; } if(arr[l]>target)return false; if(arr[l]==target)return true; r=m-1; if(matrix[r][l]<target)return false; if(matrix[r][l]==target)return true; while(i<r) { int mid=matrix[(i+r)/2][l]; int mid_index=(i+r)/2; if(mid==target)return true; else if(mid<target)i=mid_index+1; else r=mid_index; } r=l; l=0; } return false; }};
0 0
- Search a 2D Matrix II
- [刷题]Search a 2D Matrix II
- lintcode:Search a 2D Matrix II
- #leetcode#Search a 2D Matrix II
- Search a 2D Matrix II
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- Search a 2D Matrix II
- 240Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Search a 2D Matrix II
- Search a 2D Matrix II
- Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [Leetcode]Search a 2D Matrix II
- iOS开发:富文本AttributedString
- 决策树学习
- Android自带的emoji表情的使用
- hibernate —— 双向多对一映射(增/删/改数据)
- JAVA 问题及解答
- Search a 2D Matrix II
- hdu 5477 A Sweet Journey 模拟
- git使用摘要
- iOS 通用赋值model类
- CodeBlocks安装及使用
- TOF相机-非扫描三维成像
- 如何写一个框架:步骤(上)
- hdoj 4990 Reading comprehension(矩阵快速幂)
- MFC中 'CString' to 'WPARAM'之间的转换