Learning GoLang Programming: Search in a 2D Sorted Matrix

in #programming3 years ago
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.

Search a 2D sorted Matrix via GoLang


Since the rows and cols are already sorted, we can start from the top-right or lower-left corner, and move accordingly by comparing the numbers. The time complexity is O(N+M) where N and M are the number of rows or columns in the matrix resepctively.

Start search from the top-right corner:

func searchMatrix(matrix [][]int, target int) bool {
    var rows, cols = len(matrix), len(matrix[0])
    var r, c = 0, cols - 1
    for r < rows && c >= 0 {
        if matrix[r][c] == target {
            return true
        }
        if target > matrix[r][c] {
            r ++
        } else {
            c --
        }
    }
    return false
}

And start from the lower-left corner:

func searchMatrix(matrix [][]int, target int) bool {
    var rows, cols = len(matrix), len(matrix[0])
    var r, c = rows - 1, 0
    for r >= 0 && c < cols {
        if matrix[r][c] == target {
            return true
        }
        if target > matrix[r][c] {
            c ++
        } else {
            r --
        }
    }
    return false
}

We can also binary search each rows in O(NLogM) time.

See other searching the element in the sorted 2D matrix:

Reposted from Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

  1. Voting Algorithm Updated to Favor those High Delegations!
  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Coin Marketplace

STEEM 0.29
TRX 0.11
JST 0.033
BTC 63901.15
ETH 3133.40
USDT 1.00
SBD 4.05