【Leetcode】之Search a 2D Matrix
来源:互联网 发布:no热力学数据 编辑:程序博客网 时间:2024/05/19 00:12
一.问题描述
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]; }};
0 0
- 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
- Leetcode之五Search a 2D Matrix
- LeetCode 之 Search a 2D Matrix — C 实现
- leetcode之Search a 2D Matrix II
- LeetCode 之 Search a 2D Matrix II
- 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
- ARC缓存淘汰算法及其在ZFS上的实现
- 整理数学中一些名字的由来
- fastjson 学习总结
- for 循环 and while 循环(四)
- 关于Python中的for循环控制语句
- 【Leetcode】之Search a 2D Matrix
- 《Spring In Action》 读书笔记(1) -- bean装配
- iOS测试:IPV4下搭建IPV6网络 测试app在IPV4和IPV6下的兼容性
- 学习用的网址
- cookie和session的区别
- My97DatePicker时间控件使用
- android Configuration详解
- Promise系列02:Promise创建
- ffmpeg 继续学习 -- ARM优化-- AArch64