[Leetcode question record-13] Two-dimensional array after Binary Search sorting

Source: Internet
Author: User
Search a 2D matrix

Writean efficient algorithm that searches for a value inMXNMatrix. 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]
]

GivenTarget=3, Returntrue.

[Analysis-original]

/*** Creation Time: September 24, 2014 11:26:06 Project name: Test ** @ author Cao yanfeng * @ since JDK 1.6.0 _ 21 class description: check whether the sorted two-dimensional matrix has a two-layer binary search for a number, the first layer is to find the row */public class findmatrixtest {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stubint [] [] matrix = {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50 }}; system. out. println (searchmatrix (matrix, 13);} public static Boolean searchmatrix (INT [] [] matrix, int target) {int M = matrix. length; int n = matrix [0]. length; int I = 0, j = m-1; while (I <= J) {int middlerow = I + (J-I)> 1 ); if (target <matrix [middlerow] [0]) {J = middlerow-1; continue;} else if (target> matrix [middlerow] [n-1]) {I = middlerow + 1; continue;} else if (target> = matrix [middlerow] [0] & target <= matrix [middlerow] [n-1]) {return find (Matrix [middlerow], 0, n-1, Target) ;}} return false;} public static Boolean find (INT [] matrixrow, int start, int end, int target) {While (start <= END) {int middle = start + (end-Start)> 1); If (matrixrow [Middle] = target) {return true;} else if (matrixrow [Middle]> Target) {end = middle-1;} else if (matrixrow [Middle] <target) {start = middle + 1 ;}} return false ;}}


[Leetcode question record-13] Two-dimensional array after Binary Search sorting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.