-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch_a_2D_Matrix.cpp
More file actions
105 lines (95 loc) · 2.16 KB
/
Search_a_2D_Matrix.cpp
File metadata and controls
105 lines (95 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Source : https://oj.leetcode.com/problems/search-a-2d-matrix/
// Author : zheng yi xiong
// Date : 2015-01-23
/**********************************************************************************
*
* 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.
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
if (matrix.empty() || matrix[0].empty())
{
return false;
}
int row_end = matrix.size();
int col_end = matrix[0].size();
int row_begin = 0, col_begin = 0, row_mid = 0, col_mid = 0;
while (row_begin < row_end)
{
row_mid = (row_begin + row_end) / 2;
if (target == matrix[row_mid][col_end - 1])
{
return true;
}
else if (target < matrix[row_mid][col_end - 1])
{
if (target == matrix[row_mid][0])
{
return true;
}
else if (target > matrix[row_mid][0])
{
while (col_begin < col_end)
{
col_mid = (col_begin + col_end) / 2;
if (target == matrix[row_mid][col_mid])
{
return true;
}
else if (target > matrix[row_mid][col_mid])
{
col_begin = col_mid + 1;
}
else
{
col_end = col_mid;
}
}
break;
}
else
{
row_end = row_mid;
}
}
else
{
row_begin = row_mid + 1;
}
}
return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int testInt[] = { 1, 3, 5, 7,
10, 11, 16, 20,
23, 30, 34, 50};
Solution so;
vector<vector<int> > matrix(3);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
matrix[i].push_back(testInt[i * 4 + j]);
}
}
bool bFind = so.searchMatrix(matrix, 3);
return 0;
}