[leetcode] 【查找】 74. Search a 2D Matrix
2016-06-21 15:07
471 查看
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:
Given target =
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;
const size_t high=matrix.size();
const size_t len=matrix[0].size();
int begin=0,end=high*len-1,mid=0;
while(begin<end)
{
mid=(begin+end)/2;
int val=matrix[mid/len][mid%len];
if(val==target) return true;
if(val>target) end=mid;
else begin=mid+1;
}
if(matrix[begin/len][begin%len]==target ) return true;
return false;
}
};
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.
题意
判断一个矩阵中是否包含目标元素,矩阵有两个特性:从左到右排序;每一行第一个元素比上一行最后一个元素大。题解
使用二分法,把矩阵看成是一维数据处理。 长度为col*raw 用的时候下标为 mid/row mid%rowclass Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;
const size_t high=matrix.size();
const size_t len=matrix[0].size();
int begin=0,end=high*len-1,mid=0;
while(begin<end)
{
mid=(begin+end)/2;
int val=matrix[mid/len][mid%len];
if(val==target) return true;
if(val>target) end=mid;
else begin=mid+1;
}
if(matrix[begin/len][begin%len]==target ) return true;
return false;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解