码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 【Search a 2D Matrix 】python 实现

时间:2015-01-30 00:00:31      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:

题目

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.

 

代码:oj测试通过 Runtime: 75 ms

 1 class Solution:
 2     # @param matrix, a list of lists of integers
 3     # @param target, an integer
 4     # @return a boolean
 5     def searchInline(self, line, target):
 6         start = 0
 7         end = len(line)-1
 8         while start <= end :
 9             if start == end :
10                 return [False,True][line[start]==target]
11             if start+1 == end :
12                 if line[start]==target or line[end]==target :
13                     return True
14                 else:
15                     return False
16             mid=(start+end)/2
17             if line[mid]==target :
18                 return True
19             elif line[mid]>target :
20                 end = mid-1
21             else :
22                 start = mid+1
23 
24     def searchMatrix(self, matrix, target):
25         if len(matrix) == 0 :
26             return False
27         
28         if len(matrix) == 1 :
29             return self.searchInline(matrix[0], target)
30             
31         if len(matrix) == 2 :
32             return self.searchInline([matrix[1],matrix[0]][matrix[1][0]>target], target)33             
34         start = 0
35         end = len(matrix)-1
36         while start <= end :
37             if start == end:
38                 return self.searchInline(matrix[start],target)
39             if start+1 == end:
40                 if matrix[start][0] <= target and matrix[end][0] > target:
41                     return self.searchInline(matrix[start],target)
42                 if matrix[end][0] < target :
43                     return self.searchInline(matrix[end],target)
44             mid = (start+end+1)/2
45             if matrix[mid][0] <= target and matrix[mid+1][0] > target:
46                 return self.searchInline(matrix[mid],target)
47             elif matrix[mid][0] > target :
48                 end = mid-1
49             else :
50                 start = mid+1

 

思路

先按行二分查找,再按列二分查找。

代码写的比较繁琐。

leetcode 【Search a 2D Matrix 】python 实现

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4261245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!