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

Posted 安新

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Binary search, Divide and conquer--240. Search a 2D Matrix II相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 704. Binary Search

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

[Leetcode] Recover Binary Search Tree

[LeetCode] 173. Binary Search Tree Iterator_Medium_tag: Binary Search Tree

LeetCode98. Validate Binary Search Tree

Validate Binary Search Tree -- LeetCode