LeetCode OJ | Search a 2D Matrix
来源:互联网 发布:拍照软件带时间 编辑:程序博客网 时间:2024/05/29 03:10
LeetCode的这个问题可用“夹逼”的思想完成。
题目如下
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 flag = true; bool searchMatrix(vector<vector<int>>& matrix, int target) { int left = 0,right = matrix[0].size()-1, up = 0, down = matrix.size()-1; int left1 = -1,right1 = -1,up1 = -1,down1 = -1; int flag = 0; while(1) { left1 = left; right1 = right; up1 = up; down1 = down; flag = shrink(matrix,left,right,up,down,target); if(left1==left&&right1==right&&up1==up&&down1==down) break; if(flag == 1) return true; } for(int i=up;i<=down;++i) for(int j=left;j<=right;++j) if(matrix[i][j] == target) return true; return false; } int shrink(vector<vector<int>>& a,int &left,int &right,int &up,int &down,int target) { int mid = 0; for(int i=up;i<=down;++i) { if(a[i][right] > target) { up = i; break; } if(a[i][right] == target) return 1; else if(i==down) up = i; } for(int i=down;i>=up;--i) { if(a[i][left] < target) { down = i; break; } if(a[i][left] == target) return 1; else if(i==up) down = up; } for(int i=left;i<=right;++i) { if(a[down][i] > target) { left = i; break; } if(a[down][i] == target) return 1; else if(i==right) left = i; } for(int i=right;i>=left;--i) { if(a[up][i] < target) { right = i; break; } if(a[up][i] == target) return 1; else if(i==left) right = i; } return 0; }};
0 0
- LeetCode OJ:Search a 2D Matrix
- LeetCode OJ - Search a 2D Matrix
- [LeetCode OJ]Search a 2D Matrix
- LeetCode OJ Search a 2D Matrix
- LeetCode OJ | Search a 2D Matrix
- leetcode oj java Search a 2D Matrix
- leetcode oj java Search a 2D Matrix II
- LeetCode OJ-74.Search a 2D Matrix
- LeetCode OJ 240. Search a 2D Matrix II
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- (matlab)plot画图的颜色线型
- C# OOP之五 深入理解值类型和引用类型
- 正则表达式-面试
- 小易的升级之路-java
- HDU 1018 Big Number
- LeetCode OJ | Search a 2D Matrix
- LeetCode *** 127. Word Ladder(BFS)
- 池化通俗讲解
- 跟我学AngularJs:AngulaJs开发技巧汇总(持续更新)
- 二 工厂方法模式
- 编译原理:求First集与Follow集的方法
- qt项目发布
- LeetCode 57. Insert Interval/56. Merge Intervals
- SSH商城第一天的学习感受