Leetcode:search a 2D Matrix

Source: Internet
Author: User

Search a 2D Matrix

Total Accepted: 43629 submissions: 138231

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.

For example,

Consider the following matrix:

[  [1,   3,  5,  7],  [Ten, One,],  [23, 30, 34, 50]]

Given Target = 3 , return true .

Conventional train of thought, two times

BOOL Searchmatrix (vector<vector<int>>& matrix, int target) {        if (Matrix.empty ())            return False ;        Vector<int> Firstcol;        for (auto V:matrix)        firstcol.push_back (v[0]);        if (Binary_search (Firstcol.begin (), Firstcol.end (), target))            return true;         Vector<int>::iterator iter = Lower_bound (Firstcol.begin (), Firstcol.end (), target);        int low = Iter-firstcol.begin ();        for (int i = 0; i < low; i++)        {            if (Binary_search (Matrix[i].begin (), Matrix[i].end (), target))                return true;        }        return false;    }

Opportunistic, there are potential bugs

BOOL Searchmatrix (vector<vector<int> >& matrix, int target) {        int rows = Matrix.size ();        if (rows = = 0)    return false;        int cols = Matrix[0].size ();        int first = 0, last = rows * COLS-1;        if (Target < matrix[0][0] | | target > MATRIX[ROWS-1][COLS-1])            return false;        int mid, Val;        Binary search        while (first <=) {            mid = first + (Last-first)/2;            val = matrix[mid/cols][mid% cols];            if (Val > Target) Last                = mid-1;            else if (val = = target)                return true;            else First                = mid + 1;        }        return false;    }

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.