Skip to content

Commit

Permalink
add solutions for Search-a-2D-Matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
xcv58 committed Jan 11, 2015
1 parent 782a9f9 commit a1999f9
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Search-a-2D-Matrix/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <vector>
using namespace std;

class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
if (matrix.size() == 0) {
return false;
}
int n = matrix[0].size();

for (int x, y, i = 0, j = matrix.size() * n, mid; i < j; ) {
mid = (i + j) / 2;
x = mid / n;
y = mid % n;

if (matrix[x][y] == target) {
return true;
}
if (target < matrix[x][y]) {
j = mid;
} else {
i = mid + 1;
}
}
return false;
}
};

int main() {
return 0;
}
24 changes: 24 additions & 0 deletions Search-a-2D-Matrix/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0) {
return false;
}
int n = matrix[0].length;

for (int x, y, i = 0, j = matrix.length * n, mid; i < j; ) {
mid = (i + j) / 2;
x = mid / n;
y = mid % n;

if (matrix[x][y] == target) {
return true;
}
if (target < matrix[x][y]) {
j = mid;
} else {
i = mid + 1;
}
}
return false;
}
}
21 changes: 21 additions & 0 deletions Search-a-2D-Matrix/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
if len(matrix) == 0:
return False
n = len(matrix[0])
i = 0
j = n * len(matrix)
while i < j:
mid = (i + j) / 2
x = mid / n
y = mid % n
if matrix[x][y] == target:
return True
if matrix[x][y] > target:
j = mid
else:
i = mid + 1
return False

0 comments on commit a1999f9

Please sign in to comment.