leetcode [74] 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.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
题目大意:
矩阵的值是按行进行递增的,每一行从左到右也是递增的,查找一个target值是否在矩阵中存在。
解法:
我一想到这个题目,就想到使用二分查找,但是这是一个矩阵,并不是一个数组,所以将矩阵变成数组就可以了啊。
C++:
class Solution { public: bool searchVector(vector<int>v,int target,int start,int end){ if(end<start) return false; int mid=(end-start)/2+start; if(v[mid]==target) return true; else if(v[mid]<target) return searchVector(v,target,mid+1,end); else return searchVector(v,target,start,mid-1); } bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()||matrix[0].empty()) return false; vector<int>v; for(int i=0;i<matrix[0].size();i++) v.push_back(matrix[0][i]); for(int i=1;i<matrix.size();i++){ v.insert(v.end(),matrix[i].begin(),matrix[i].end()); } return searchVector(v,target,0,v.size()-1); } };
这种二分查找虽然是对的,但我总觉得,这样做不太好,用了很多额外的空间,应该转换成为矩阵的二分查找。
改进后的C++:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()||matrix[0].empty()) return false; int m=matrix.size(); int n=matrix[0].size(); if (matrix[0][0]>target||matrix[m-1][n-1]<target) return false; int start=0,end=m*n-1; int mid,midRow,midCol; while(start<=end){ mid=start+(end-start)/2; midCol=mid%n; midRow=mid/n; if(matrix[midRow][midCol]<target) start=mid+1; else if(matrix[midRow][midCol]>target) end=mid-1; else return true; } return false; } };
Python:
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or target is None: return False m,n=len(matrix),len(matrix[0]) mid=midCol=midRow=0 start,end=0,m*n-1 while start<=end: mid=(start+end)/2 midCol=mid%n midRow=mid/n if matrix[midRow][midCol]<target: start=mid+1 elif matrix[midRow][midCol]>target: end=mid-1 else: return True return False