【劍指offer】Java實現

來源:互聯網
上載者:User

標籤:int   size   遍曆   尋找   str   leetcode   closed   簡單的   面試題   

面試題3 二維數組中的尋找 Leetcode--74 Search a 2D Matrix

 

 1 /*Java 2 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3  4     Integers in each row are sorted from left to right. 5     The first integer of each row is greater than the last integer of the previous row. 6  7 For example, 8  9 Consider the following matrix:10 11 [12   [1,   3,  5,  7],13   [10, 11, 16, 20],14   [23, 30, 34, 50]15 ]16 17 Given target = 3, return true.18 本題最簡單的方法迴圈遍曆行與列 但是時間複雜度較高。19 */20 class Solution {21     public boolean searchMatrix(int[][] matrix, int target) {22         boolean find = false;23         int rows,cols;24         if (matrix == null || matrix.length==0) {25             rows = 0;26             cols = 0;27         } else {28             rows = matrix.length;29             cols = matrix[0].length;30         }31             32         if (matrix != null && rows > 0 && cols > 0) {33             int row = 0;34             int col = cols-1;35             while(row<rows && col>=0){36                 if(matrix[row][col]==target){37                     find=true;38                     break;39                 }40                     41                 else if(matrix[row][col]>target){42                     col--;43                 }else{44                     row++;45                 }46             }47         }48 49         return find;50     }51 public static void main(String[] args) {52         int[][] matrix1 = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };53 54         int[][] matrix = {};55         int target = 55;56         SearchA2DMatrix cc = new SearchA2DMatrix();57         boolean find = cc.searchMatrix(matrix, target);58         System.out.println(find);59     }60 }
View Code

 

【劍指offer】Java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.