博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Search a 2D Matrix
阅读量:4551 次
发布时间:2019-06-08

本文共 1287 字,大约阅读时间需要 4 分钟。

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.

1.迭代

class Solution {public:    bool searchMatrix(vector
>& matrix, int target) { int m = matrix.size(); int n = m==0 ? 0:matrix[0].size(); int i=0,j=n-1; while(i
=0){ if(matrix[i][j] < target) i++; else if(matrix[i][j] > target) j--; else return true; } return false; }};

 

2.递归

class Solution {public:    bool searchMatrix(vector
>& matrix,int r,int c,int target){ if(c<0 || r >= matrix.size()){ return false; } if(matrix[r][c]>target){ return searchMatrix(matrix,r,c-1,target); }else if(matrix[r][c]
>& matrix, int target) { int m = matrix.size(); if(m==0){ return false; } int n = matrix[0].size(); return searchMatrix(matrix,0,n-1,target); }};

 

转载于:https://www.cnblogs.com/zengzy/p/5005720.html

你可能感兴趣的文章
Margin
查看>>
完成登录与注册页面的前端
查看>>
centos 源码安装php7
查看>>
Log4j详细教程
查看>>
UVa-1368-DNA序列
查看>>
ConfigParser模块
查看>>
如何开发优质的 Flutter App:Flutter App 软件测试指南
查看>>
决胜Flutter 第一章 熟悉战场
查看>>
如何开发优质的 Flutter App:Flutter App 软件调试指南
查看>>
决胜经典算法之冒泡排序
查看>>
决胜经典算法之选择排序
查看>>
11、求二进制中1的个数
查看>>
【nodejs】让nodejs像后端mvc框架(asp.net mvc)一样处理请求--请求处理结果适配篇(7/8)...
查看>>
CodeForces 731A Night at the Museum
查看>>
MySQL 删除数据库
查看>>
JavaScript 字符串(String) 对象
查看>>
How to use VisualSVN Server and TortoiseSVN to host your codes and control your codes' version
查看>>
微信小程序picker组件 - 省市二级联动
查看>>
Dynamics CRM 给视图配置安全角色
查看>>
Eclipse修改已存在的SVN地址
查看>>