【Leetcode】之Search a 2D Matrix
2016-06-15 10:56
519 查看
一.问题描述
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 row_num = matrix.size(); if(row_num==0) return 0; int line_num = matrix[0].size(); int total_num = row_num*line_num; int st=0;int end=total_num-1;int mid; while(st<end){ mid = (st+end)/2; int curr_val = gen_val(matrix,mid); if(curr_val==target) return 1; if(curr_val<target) st=mid+1; if(curr_val>target) end=mid-1; } if(st==end){ int curr_val = gen_val(matrix,st); if(curr_val==target) return 1; else return 0; } return 0; } int gen_val(vector<vector<int>>& matrix, int idx){ int row_num = matrix.size(); int line_num = matrix[0].size(); int i,j; i=idx/line_num; j=idx-i*line_num; return matrix[i][j]; } };
相关文章推荐
- 二、linux vi编辑常用命令
- Makefile Implicit Rules
- android Configuration详解
- dataset填充msflexgrid
- 适配器模式
- Eclipse Kepler中配置JadClipse
- POI导入
- Promise系列02:Promise创建
- 《Spring In Action》 读书笔记(1) -- bean装配
- 关于Python中的for循环控制语句
- for 循环 and while 循环(四)
- C#用递归算法解决经典背包问题
- 回调的运用
- React Native:从入门到原理
- 《软件工程》课程的总结
- Tomcat卸载
- SVN工程状态标记消失问题
- 印迹拉长处理办法
- 一、linux 常用命令
- Sparse Coding