Leetcode---Search a 2D Matrix

Source: Internet
Author: User

Topic:

Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:

    • Integers in each row is sorted from the left to the right.
    • The first integer of each row was greater than the last integer of the previous row.

Package Leetcode;

public class Searcha2dmatrix {
Array Lookup: 1, good order (two points to find the premise) 2, two points to find!
public static Boolean Searchmatrix (int[][] matrix, int target) {
int m = 0;
while (m<=matrix.length-1) {
if (matrix[m][0]<=target&&matrix[m][matrix[0].length-1]>=target) {
return binary (matrix[m],0,matrix[0].length-1,target);
}else
m++;
}
return false;
}

public static Boolean binary (int nums[], int left,int right,int tar) {//Two-point lookup general algorithm
while (Right>=left) {
int mid = (right+left)/2;
if (nums[mid] = = tar) return true;
if (Nums[mid] >tar) return binary (Nums,left,mid-1,tar);
return binary (Nums,mid+1,right,tar);
}
return false;
}

public static void Main (string[] args) {
TODO auto-generated Method Stub

Int[][] a ={
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50}
};
System.out.print (Searchmatrix (a,9));
}

}

Leetcode---Search a 2D Matrix

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.