leetcodeOJ 240. Search a 2D Matrix II
来源:互联网 发布:沪江背单词软件 编辑:程序博客网 时间:2024/06/06 19:53
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
.
代码如下:
/*思路:每次将矩阵中心的元素与目标值比较,将矩阵分成四部分:左上、左下、右上、右下 */class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if(m == 0) return false; int n = matrix[0].size(); if(n == 0) return false; int up = 0; int down = m-1; int left = 0; int right = n-1; bool ans = search(matrix, target, up, down, left, right); return ans; }private: bool search(vector<vector<int>>& matrix, int target, int up, int down, int left, int right){ if(up == down && left == right) return (target == matrix[up][left]); if(up>down || left > right) return false; int midRow = up + (down-up)/2; int midCol = left + (right-left)/2; if(target == matrix[midRow][midCol]){ return true; } else if(target < matrix[midRow][midCol]){ return search(matrix, target, up, down, left, midCol-1) || search(matrix, target, up, midRow-1, midCol, right); } else{ return search(matrix, target, up, midRow, midCol+1, right) || search(matrix, target, midRow+1, down, left, right); } }};
另一种比较高效的方法:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if(m == 0) return false; int n = matrix[0].size(); if(n == 0) return false; int i = 0; int j = n -1; while(i < m && j >= 0){ if(target == matrix[i][j]) return true; else if(target > matrix[i][j]){ i++; } else{ j--; } } return false; }};
0 0
- leetcodeOJ 240. Search a 2D Matrix II
- leetcodeOJ 74. Search a 2D Matrix
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- java基础总结第一个程序
- php单引号和双引号的区别
- 第二周初学表格
- android 微信分享问题
- Fresco图片加载库常见问题
- leetcodeOJ 240. Search a 2D Matrix II
- Atom如何实时渲染界面(markdown,html)
- 网易笔试有感
- 总算开始了
- 以下哪种数据结构的查找效率最高
- 综合——3.25
- Standford 机器学习—第四讲 神经网络的表示
- 蓝桥杯搭积木全排列
- 初学linux ---浅谈进程