careercup-Sorting and finding 11.6

Source: Internet
Author: User

11.6 Given the m*n matrix, each row and column is sorted in ascending order, please write code to find out an element.

Similar to leetcode:search a 2D Matrix but unlike the one in Leetcode, the first element of the next line is not necessarily greater than the last element in the previous row. So using binary search is a bit of a hassle.

Solution One: By observing we know:

If the beginning of the column is greater than X, then x is on the left side of the column;

If the end of the column is less than x, then x is on the right side of the column;

If the beginning of the line is less than x, then x is above the row;

If the end of the line is less than x, then x is below the row

We can start the search from anywhere, but let's start with the starting element of the column.

We need to start with the largest column and then move to the left, which means that the first element to compare is array[0][c-1], where C is the number of columns.

C + + Implementation code:

#include <iostream>#include<vector>using namespacestd;BOOLFINDELEMEMT (vector<vector<int> > &matrix,inttarget) {    if(Matrix.empty () | | matrix[0].empty ())return false; intm=matrix.size (); intn=matrix[0].size (); introw=0; intcol=n-1;  while(row<m&&col>=0)    {        if(matrix[row][col]==target)return true; if(matrix[row][col]<target) Row++; ElseCol--; }    return false;}intmain () {vector<vector<int> > vec={{ the, -, +, -},{ -, *, the, the},{ -, -, the, the},{ +, the, -, -}}; cout&LT;&LT;FINDELEMEMT (VEC, -) <<Endl;}

careercup-Sorting and finding 11.6

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.