Leetcode: Search a 2D Matrix
来源:互联网 发布:mastercamx9编程技巧 编辑:程序博客网 时间:2024/06/05 07:14
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
.
二分查找。
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int rows = matrix.size(); if (rows == 0) return false; int cols = matrix[0].size(); if (cols == 0) return false; bool result = false; int low_row = 0, up_row = rows - 1; int low_col = 0, up_col = cols - 1; int mid_row, mid_col; while (low_row <= up_row) { mid_row = (low_row + up_row) / 2; if (matrix[mid_row][up_col] == target) { return true; } else if (matrix[mid_row][up_col] < target) { low_row = mid_row + 1; } else { if (matrix[mid_row][low_col] == target) { return true; } else if (matrix[mid_row][low_col] < target) { low_row = up_row = mid_row; ++low_col; --up_col; while (low_col <= up_col) { mid_col = (low_col + up_col) / 2; if (matrix[mid_row][mid_col] == target) { return true; } else if (matrix[mid_row][mid_col] < target) { low_col = mid_col + 1; } else { up_col = mid_col - 1; } } return false; } else { up_row = mid_row - 1; } } } return false; }};
==================第二次====================
把Matrix看做一个数组来考虑,简单的二分查找。
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) { return false; } int rows = matrix.size(); int cols = matrix[0].size(); int low = 0; int up = rows * cols - 1; int mid, midx, midy; while (low <= up) { mid = low + (up - low) / 2; midx = mid / cols; midy = mid % cols; if (matrix[midx][midy] == target) { return true; } else if (matrix[midx][midy] < target) { low = mid + 1; } else { up = mid - 1; } } return false; }};
0 0
- [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
- [Leetcode] Search a 2-D 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:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 转:免费WIFI卡位战升温:互联网巨头新一轮圈地
- 关于MySQL的load data infile
- onpaste事件的浅谈
- 二叉查找树
- 拓胜第十九天
- Leetcode: Search a 2D Matrix
- 三十六 fflush(stdout);
- 插入排序
- DR BDR
- firefox的sqlite插件
- L2_lines_in
- 常见设备在linux中的文件名
- cf-208B - Solitaire-记录状态DFS
- 三十七 sysconf()函数应用举例:查看CPU及内存信息