码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Search 2D Matrix

时间:2015-05-03 21:49:12      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> >& matrix, int target) {
 4         int col=matrix[0].size();
 5         int row=matrix.size();
 6         
 7         int targetrow=0;
 8         int flag=0;
 9 
10 
11         if(0==col-1&&0==row-1)
12         {
13             if(target==matrix[0][0])
14                 return true;
15             else
16                 return false;
17         }
18 
19 
20         for(int i=0;i<row;i++)
21         {
22             if(target<matrix[0][0])
23             {
24                 return false;
25             }
26             if(target==matrix[i][0])
27             {
28                 return true;
29             }
30             if(target<matrix[i][0]&&i>=1)
31             {
32                 flag=1;
33                 targetrow=i-1;
34                 break;
35             }
36             if(target<matrix[row-1][col-1])
37             {
38                 flag=1;
39                 targetrow=row-1;
40             }
41             if(target==matrix[row-1][col-1])
42             {
43                 return true;
44             }
45             flag=0;
46         }
47 
48 
49         for(int i=0;i<col;i++)
50         {
51             if(target==matrix[targetrow][i])
52             {
53                 flag=1;
54                 break;
55             }
56             flag=0;
57         }
58 
59         if(0==flag)
60             return false;
61         else
62             return true;
63     }
64 };

 

【leetcode】Search 2D Matrix

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4474682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!