LeetCode 之 Search a 2D Matrix — C 实现
来源:互联网 发布:北大青鸟java培训课程 编辑:程序博客网 时间:2024/05/19 02:02
Search a 2D Matrix
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, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
给定 target = 3,返回 false。
分析:
采用二分查找。
难点在于对于 mid 求出其在矩阵中对应的行和列。
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { int low = 0, high = matrixRowSize * matrixColSize - 1; int mid = 0, midRow = 0, midCol = 0; if(!matrix || (matrixRowSize * matrixColSize == 0))/*空指针或空矩阵*/ { return false; } /***二分查找***/ while(low <= high) { mid = (low + high)/2; midRow = mid / matrixColSize; /*属于所在行*/ midCol = mid - midRow * matrixColSize; /*属于所在列*/ if(matrix[midRow][midCol] == target) { return true; } else if(matrix[midRow][midCol] < target) { low = mid + 1; } else { high = mid - 1; } } return false;}
0 0
- LeetCode 之 Search a 2D Matrix — C 实现
- 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 之Search a 2D Matrix
- [leetcode][Search] Search a 2D Matrix
- [C++]LeetCode: 61 Search a 2D Matrix
- [leetcode-240]Search a 2D Matrix II(C语言)
- leetcode 240: Search a 2D Matrix II C++Version
- [leetcode-74]Search a 2D Matrix(c)
- [C语言][LeetCode][74]Search a 2D Matrix
- Java 实现leetcode Search a 2D Matrix II
- Leetcode之五Search a 2D Matrix
- leetcode之Search a 2D Matrix II
- LeetCode 之 Search a 2D Matrix II
- Android 开发 根据activity前台状态显示通知栏信息或对话框(推送/本地service)
- Oracle删除当前用户下所有的表的方法
- Win7下vc++6.0打开项目Microsoft(R) Developer Studio以及Unable to register this add-in because its DLLRegist
- POJ 2318 TOYS 叉积运算+二分
- postfix反垃圾邮件
- LeetCode 之 Search a 2D Matrix — C 实现
- 性能测试新手误区(五)
- MFC 串口编程
- Chrome for Android在Chromium代码库中的提交patch
- 性能测试新手误区(六)
- js当前日期加几天自动计算并自增月份和年
- iPhone 6的自适应布局
- centos下top安装
- Oracle中添加新用户