Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit75193fd

Browse files
authored
Merge pull requestneetcode-gh#1265 from Abusagit/main
Update search_a_2d_matrix.cpp
2 parentsd6804d9 +32e2ea6 commit75193fd

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎cpp/neetcode_150/05_binary_search/search_a_2d_matrix.cpp‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,41 @@ class Solution {
4747
returnfalse;
4848
}
4949
};
50+
51+
// Same approach with implicit array linearization
52+
// T(n) = O(log_2(mn)) = O(log_2(m) + log_2(n))
53+
classSolution {
54+
public:
55+
boolsearchMatrix(vector<vector<int>>& matrix,int target) {
56+
57+
int left =0;
58+
int m = matrix.size();
59+
int n = matrix[0].size();
60+
int right = m * n -1;
61+
62+
while (left <= right){
63+
64+
int middle = right + (left - right) /2;
65+
66+
// compute sub-indices using matrix structure
67+
int row = middle / n;
68+
int col = middle % n;
69+
70+
71+
//ordinary binary search
72+
int middle_x = matrix[row][col];
73+
if (target > middle_x){
74+
left = ++middle;
75+
}elseif (target < middle_x){
76+
right = --middle;
77+
}else {
78+
returntrue;
79+
}
80+
81+
82+
}
83+
84+
returnfalse;
85+
86+
}
87+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp