Learning GoLang Programming: Search in a 2D Sorted Matrix
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:
- How to Search in 2D Sorted Matrix?
- https://helloacm.com/teaching-kids-programming-search-in-a-2d-sorted-matrix/
- GoLang: Search a 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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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
amazing
[WhereIn Android] (http://www.wherein.io)