【題目描述】
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.
寫出一個高效的算法來搜索 m × n矩陣中的值。
這個矩陣具有以下特性:每行中的整數從左到右是排序的。每行的第一個數大於上一行的最後一個整數。
【題目鏈接】
http://www.lintcode.com/en/problem/search-a-2d-matrix/
【題目解析】
對於這個給定的矩陣,我們如果用brute force解法,用兩個嵌套循環,O(n2)便可以得到答案.但是我們需要注意的是這道題已經給定了這個矩陣的兩個特性,這兩個特性對於提
高我們算法的時間複雜度有很大幫助,首先我們給出一個O(n)的解法,也就是說我們可以固定住右上角的元素,根據遞增或者遞減的規律,我們可以判斷這個給定的數值是否存在於這個矩陣當中.
【參考答案】
http://www.jiuzhang.com/solutions/search-a-2d-matrix/