LeetCode 74.Search a 2D Matrix Java

來源:互聯網
上載者:User

標籤:boolean   system   follow   java   chm   二維數組   bin   二分尋找   長度   

題目:

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的矩陣,其中矩陣的特點為:(1)每一行從小到大有序排列 (2)每一行的第一位元都比前一行的數大,要求寫出一個在矩陣中判定某元素是否存在的演算法。因為這個矩陣具有的特點,我們可以把這個矩陣直接看成一個一維數組newArray,長度為m*n, 其中newArray[x]可以對應到矩陣的matrix[x/列數][x%列數]。然後直接對newArray使用二分尋找即可。需要注意的是,當矩陣為空白時,需要直接返回false。

 

代碼:

public class Solution {public boolean searchMatrix(int[][] matrix, int target) {if(matrix.length==0){return false;}        int col=matrix[0].length;//數組列數        int row=matrix.length;//數組行數                int[] newArray=new int[row*col];//將二維數組放到一個一維素中,newArray[i]對應二維數組中的matrix[i/n][i%n]                return binarySearch(matrix,newArray,target);    }public boolean binarySearch(int[][] matrix,int[] newArray,int target) {int length=newArray.length;int col=matrix[0].length;//數組列數int low=0;int high=length-1;while(low<=high){int mid=(low+high)/2;if(matrix[mid/col][mid%col]<target){low=mid+1;}else if(matrix[mid/col][mid%col]>target){high=mid-1;}else{//System.out.println("find: "+target);return true;}}//System.out.println("not find: "+target);return false;}}

  

LeetCode 74.Search a 2D Matrix 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.