[Leetcode]Search a 2D Matrix II
2015-11-19 14:36
330 查看
Search a 2D Matrix II My Submissions Question
Total Accepted: 19946 Total Submissions: 64757 Difficulty: Medium
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
Subscribe to see which companies asked this question
当时看到这道题 我的想法是这样的,如下代码(p.s 实现的时候遇到了各种细节问题,下面是discuss中的)
后来看到大神写的是这样的。。。
果然还停留在菜鸟水平,做完怀疑了一晚的智商
Total Accepted: 19946 Total Submissions: 64757 Difficulty: Medium
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
Subscribe to see which companies asked this question
当时看到这道题 我的想法是这样的,如下代码(p.s 实现的时候遇到了各种细节问题,下面是discuss中的)
class Solution { public: bool search(vector<vector<int>> &matrix,int si,int ei,int sj,int ej,int target){ if(si>ei || sj>ej || matrix[si][sj] > target || matrix[ei][ej] < target) return false; //si is up side,ei is down side,sj is left side, ej is right side int mi = (si + ei) / 2; int mj = (sj + ej) / 2; if(matrix[mi][mj] == target) return true; else if(matrix[mi][mj] < target){ return search(matrix,si,mi,mj+1,ej,target) ||search(matrix,mi+1,ei,sj,mj,target)||search(matrix,mi+1,ei,mj+1,ej,target); } else{ return search(matrix,si,mi-1,mj,ej,target) ||search(matrix,mi,ei,sj,mj-1,target) ||search(matrix,si,mi-1,sj,mj-1,target); } } bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()) return false; return search(matrix,0,matrix.size()-1,0,matrix[0].size()-1,target); } };
后来看到大神写的是这样的。。。
bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(), n = matrix[0].size(); int i = 0, j = n - 1; // search target from up-right side to down-left side while (i <= m-1 && j >= 0) { if (matrix[i][j] == target) return true; else if (matrix[i][j] > target) --j; else // matrix[i][j] < target ++i; } return false; }
果然还停留在菜鸟水平,做完怀疑了一晚的智商
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#获取关键字附近文字算法实例