首页 > 其他 > 详细

[Leetcode] Binary search, Divide and conquer--240. Search a 2D Matrix II

时间:2017-06-11 00:51:30      阅读:374      评论: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 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.

Solution:

  1. 1st idea use one binary search

   iterate every rows , binary search from row i to find the insertion position p (bisect_right)

   m = len(matrix), n = len(matrix[0]) time complexity O(m*logn)
技术分享
 1  if len(matrix) == 0 or len(matrix[0]) == 0:
 2             return False
 3         i = 0
 4         while (i < len(matrix)):
 5             pos = bisect_right(matrix[i], target)            #use binary search
 6             #print(" aaas: ",i, pos-1)
 7             if matrix[i][pos-1] == target:
 8                 return True
 9             i += 1
10         return False
View Code

 

2. 2nd utilize the ordered row and column,  start from bottom left value v, if v is bigger than target, then go the upper column, else go the right row. time complexity o(m+n)

 
技术分享
 1 if len(matrix) == 0 or len(matrix[0]) == 0:
 2             return False
 3         m = len(matrix)
 4         n = len(matrix[0])
 5         i = m-1             #row
 6         j = 0           #column
 7         while ( i >= 0 and j <= n-1):
 8             if matrix[i][j] == target:
 9                 return True
10             elif matrix[i][j] > target:
11                 i -= 1
12             else:
13                 j += 1
14         return False
View Code

 

3. we can also use divide and conquer:

   reference:

 

 

[Leetcode] Binary search, Divide and conquer--240. Search a 2D Matrix II

原文:http://www.cnblogs.com/anxin6699/p/6980421.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!