LeetCode 74. Search a 2D 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.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.

題目

寫出一個高效的算法來搜索 m × n矩陣中的值处嫌。
這個矩陣具有以下特性:

  • 每行中的整數(shù)從左到右是排序的稽寒。
  • 每行的第一個數(shù)大于上一行的最后一個整數(shù)翔横。
    樣例
    考慮下列矩陣:
[
  [1, 3, 5, 7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

給出 target = 3,返回 true

分析

本題主要考察的是二分法或详,但是這里如何使用二分法又有不同的策略,但本質(zhì)都是一樣的
方法一胜臊,我們二分问麸,先從每列的最后一個數(shù)開始,確定它的列再搜索行
方法二阵谚,就是將二維數(shù)組展開一維數(shù)組蚕礼,然后二分法中間的數(shù)
方法三烟具,就是分別求行和列,求行時奠蹬,用二分法净赴,然后求列在用二分法。

代碼

方法一

public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if(matrix == null)
            return false;
        int rows=matrix.length;
        if(rows == 0 )
            return false;
        // 行數(shù)     
        int cols=matrix[0].length;  // 列數(shù)        
        int i=0, j=cols-1;    
        boolean found = false;    
        while(j>=0 && j<cols && i<rows)   //  i>=0 默認滿足罩润,無須再判斷     
        {    
            if(matrix[i][j] == target) { found = true;  break; }                   
            else if(matrix[i][j] > target) j--;  // 如果矩陣右上角的值比target大,刪除所在的列翼馆,列號-1     
            else i++;                           // 如果矩陣右上角的值不大于target割以,刪除所在的行,行號+1    
        }                 
        return found;
        
    }
}

方法二

public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if (matrix == null || matrix.length == 0) {
            return false;
        }
        if (matrix[0] == null || matrix[0].length == 0) {
            return false;
        }
        
        int row = matrix.length, column = matrix[0].length;
        int start = 0, end = row * column - 1;
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int number = matrix[mid / column][mid % column];
            if (number == target) {
                return true;
            } else if (number < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        if (matrix[start / column][start % column] == target) {
            return true;
        } else if (matrix[end / column][end % column] == target) {
            return true;
        }
        
        return false;
    }
}

方法三

public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if (matrix == null || matrix.length == 0) {
            return false;
        }
        if (matrix[0] == null || matrix[0].length == 0) {
            return false;
        }
        
        int row = matrix.length;
        int column = matrix[0].length;
        
        // find the row index, the last number <= target 
        int start = 0, end = row - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (matrix[mid][0] == target) {
                return true;
            } else if (matrix[mid][0] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        if (matrix[end][0] <= target) {
            row = end;
        } else if (matrix[start][0] <= target) {
            row = start;
        } else {
            return false;
        }
        
        // find the column index, the number equal to target
        start = 0;
        end = column - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (matrix[row][mid] == target) {
                return true;
            } else if (matrix[row][mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        if (matrix[row][start] == target) {
            return true;
        } else if (matrix[row][end] == target) {
            return true;
        }
        return false;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末应媚,一起剝皮案震驚了整個濱河市严沥,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌中姜,老刑警劉巖消玄,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異丢胚,居然都是意外死亡翩瓜,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門携龟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來兔跌,“玉大人,你說我怎么就攤上這事峡蟋》匚Γ” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵蕊蝗,是天一觀的道長仅乓。 經(jīng)常有香客問我,道長蓬戚,這世上最難降的妖魔是什么夸楣? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮子漩,結(jié)果婚禮上裕偿,老公的妹妹穿的比我還像新娘。我一直安慰自己痛单,他們只是感情好嘿棘,可當我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著旭绒,像睡著了一般鸟妙。 火紅的嫁衣襯著肌膚如雪焦人。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天重父,我揣著相機與錄音花椭,去河邊找鬼。 笑死房午,一個胖子當著我的面吹牛矿辽,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播郭厌,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼袋倔,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了折柠?” 一聲冷哼從身側(cè)響起宾娜,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎扇售,沒想到半個月后前塔,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡承冰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年华弓,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片困乒。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡该抒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出顶燕,到底是詐尸還是另有隱情凑保,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布涌攻,位于F島的核電站欧引,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏恳谎。R本人自食惡果不足惜芝此,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望因痛。 院中可真熱鬧婚苹,春花似錦、人聲如沸鸵膏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽谭企。三九已至廓译,卻和暖如春评肆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背非区。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工瓜挽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人征绸。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓久橙,卻偏偏與公主長得像,于是被迫代替她去往敵國和親管怠。 傳聞我的和親對象是個殘疾皇子淆衷,可洞房花燭夜當晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容