zoukankan      html  css  js  c++  java
  • [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:

     
  • 相关阅读:
    Ubuntu下cc和gcc的关系
    Ubuntu下makefile的简单使用
    Ubuntu下配置Apache以及搭载CGI
    Easy C 编程 in Linux
    Ubuntu下配置GitHub
    Ubuntu学习之路2
    Ubuntu下配置Java环境
    Vim学习之路1
    将博客搬至CSDN
    ubuntu连接手机的方法
  • 原文地址:https://www.cnblogs.com/anxin6699/p/6980421.html
Copyright © 2011-2022 走看看