本文準備講解1個算法編程問題, 這個算法編程問題來自LintCode平臺。不了解.LintCode平臺的讀者可以閱讀筆者文章(在線編程平臺推薦-LeetCode)。問題的英文版本描述如下:
Search a 2D Matrix II
Write an efficient algorithm that searches an m x n matrix, return the occurrence count of targets.
This matrix has the following properties:
Integers in each row are sorted from left to right.
Integers in each column are sorted from up to bottom.
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
Given target =3, return 2.
搜索二維矩陣?II
搜索m×n矩陣。
這個矩陣具有以下特性:
Integers in each row are sorted from left to right.
Integers in each column are sorted from up to bottom.
樣例
考慮下列矩陣:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
給出 target =3,返回?2.
面對2維矩陣,首先需要找到目標元素所在的矩陣行。每個矩陣行都為升序數列,矩陣的首列也為升序數列。找到目標元素所在的矩陣行需要搜索矩陣首列。然后需要找到目標元素所在的位置。找到目標元素所在的矩陣位置需要搜索目標元素所在的矩陣行。JAVA 語言提供的數組搜索函數只能找到目標數組元素。面對本問題,找到目標元素所在的矩陣行不能選用 JAVA 語言提供的數組搜索函數;找到目標元素所在的矩陣位置可以選用 JAVA 語言提供的數組搜索函數。該算法不能處理行內字符重復出現。 ( 參見另1個問題的文章:LintCode問題圖解-20。?)
搜索二維矩陣?II 問題和搜索二維矩陣問題都不能對應通用的搜索二維矩陣問題,通用的搜索二維矩陣問題需要選用更多的測試用例。