本文準備講解1個算法編程問題乓梨, 這個算法編程問題來自LintCode平臺鳖轰。不了解.LintCode平臺的讀者可以閱讀筆者文章(在線編程平臺推薦-LeetCode)。問題的英文版本描述如下:
Search a 2D Matrix
Write an efficient algorithm that searches an?mxn?matrix for a value.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integers from each row are sorted .
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target 3, return true.
搜索二維矩陣
搜索?m×n?矩陣扶镀。
這個矩陣具有以下特性:
Integers in each row are sorted from left to right.
The first integers from each row are sorted .
樣例
考慮下列矩陣:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
給出 target 3蕴侣,返回 true.
面對2維矩陣,首先需要找到目標元素所在的矩陣行臭觉。每個矩陣行都為升序數(shù)列昆雀,矩陣的首列也為升序數(shù)列。找到目標元素所在的矩陣行需要搜索矩陣首列蝠筑。然后需要找到目標元素所在的位置狞膘。找到目標元素所在的矩陣位置需要搜索目標元素所在的矩陣行。JAVA 語言提供的數(shù)組搜索函數(shù)只能找到目標數(shù)組元素什乙。面對本問題挽封,找到目標元素所在的矩陣行不能選用 JAVA 語言提供的數(shù)組搜索函數(shù);找到目標元素所在的矩陣位置可以選用 JAVA 語言提供的數(shù)組搜索函數(shù)臣镣。