标签:
题目来源:
https://leetcode.com/problems/search-a-2d-matrix/
题意分析:
给一个m×n矩阵,矩阵是按照从小到大排列,也就是a[i][j]和a[m][n]如果i > m则a[i][j]>a[m][n],如果i == m,j > n,则a[i][j]>a[m][n]。
题目思路:
利用二分查找,首先确定在那个行,然后继续二分查找。
代码(Python):
1 class Solution(object): 2 def searchMatrix(self, matrix, target): 3 """ 4 :type matrix: List[List[int]] 5 :type target: int 6 :rtype: bool 7 """ 8 m = len(matrix) 9 if m == 0: 10 return False 11 n = len(matrix[0]) 12 if n == 0: 13 return False 14 mfirst,mlast = 0,m - 1 15 while mfirst < mlast: 16 mid = (mfirst + mlast + 1) // 2 17 if matrix[mid][0] == target: 18 return True 19 if matrix[mid][0] < target: 20 mfirst = mid 21 else: 22 mlast = mid - 1 23 print(mfirst) 24 nfirst,nlast = 0,n - 1 25 while nfirst <= nlast: 26 mid = (nfirst + nlast) // 2 27 if matrix[mfirst][mid] == target: 28 return True 29 if matrix[mfirst][mid] < target: 30 nfirst = mid + 1 31 else: 32 nlast = mid - 1 33 return False
转载请注明出处:http://www.cnblogs.com/chruny/p/5069802.html
[LeetCode]题解(python):074-Search a 2D Matrix
标签:
原文地址:http://www.cnblogs.com/chruny/p/5069802.html