CCI: Find in Matrix
来源:互联网 发布:诡异事件 知乎 编辑:程序博客网 时间:2024/05/21 10:07
Given a matrix in which each row and each column is sorted, write a method to find an element in it.
第一反应是取矩阵中间元素折半,可以去掉1/4的区域,不过这样一来剩下的就是两个矩阵了。虽然也可以解决问题,有些复杂。简单一些,O(m+n)的方案吧。
注意二维数组做参数的用法,折腾了好几次,有时间再看看有没有更好的方式。
bool findInMatrix(int A[][5], int rows, int cols, int target) {int i = 0;int j = cols - 1;while (i < rows && j >= 0) {if (A[i][j] == target) {return true;}else if (A[i][j] > target) {--j;}else {++i;}}return false;}int _tmain(int argc, _TCHAR* argv[]){int rows = 3, cols = 5;int A[3][5] = {{1, 8, 12, 20, 30},{4, 9, 13, 25, 32},{6, 11,19, 28, 40},};cout << "Number 0 " << (findInMatrix(A, rows, cols, 5) ? "found" : "not found") << endl;cout << "Number 19 " << (findInMatrix(A, rows, cols, 19) ? "found" : "not found") << endl;cout << "Number 25 " << (findInMatrix(A, rows, cols, 25) ? "found" : "not found") << endl;cout << "Number 40 " << (findInMatrix(A, rows, cols, 40) ? "found" : "not found") << endl;cout << "Number 45 " << (findInMatrix(A, rows, cols, 45) ? "found" : "not found") << endl;return 0;}
0 0
- CCI: Find in Matrix
- CCI: Count negative numbers in matrix
- Find Elements in Matrix
- CCI: Find maximum subsquare
- Find Elements in Matrix-LintCode
- find duplicates in matrix within k indices
- [LinkedIn] Find target number in 2D sorted array (matrix)
- find path/route in a maze 2 d matrix
- Algs4-1.4.18 Find local minimum in n x n matrix in O(n) time
- Matrix structure in XNA
- view Matrix in opengl
- Matrix multiplication in OpenCV
- Matrix In OpenGL
- matrix inversion in boost
- B. OR in Matrix
- B. OR in Matrix
- B. OR in Matrix
- 【COderForces】OR in Matrix
- JAVA String.format 方法使用介绍
- 02 Unity3d脚本功能--《程序员学Unity3d》
- linux(学习笔记)
- RH318之创建模板
- Combination Sum II
- CCI: Find in Matrix
- Java 编写 约瑟夫环(Joseph Ring)游戏
- cygwin 镜像文件下载地址
- php图片裁剪问题
- 分享 10段实用的HTML5代码
- matlab 使用大全,随机,文件,运算(一)
- Basic remains
- linux通配符
- 敏捷开发之道(三)极限编程XP续