Skip to content

Commit c555907

Browse files
committed
add: LocalMaximaInArray and MatrixSearch
1 parent a13c269 commit c555907

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
public class LocalMaximaInArray {
2+
public int localMaximaInArray(int[] nums) {
3+
int left = 0;
4+
int right = nums.length - 1;
5+
while (left < right) {
6+
int mid = (left + right) / 2;
7+
if (nums[mid] > nums[mid + 1]) {
8+
right = mid;
9+
} else {
10+
left = mid + 1;
11+
}
12+
}
13+
return left;
14+
}
15+
}

java/Binary Search/MatrixSearch.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
public class MatrixSearch {
2+
public boolean matrixSearch(int[][] matrix, int target) {
3+
int m = matrix.length;
4+
int n = matrix[0].length;
5+
int left = 0;
6+
int right = m * n - 1;
7+
// Perform binary search to find the target.
8+
while (left <= right) {
9+
int mid = (left + right) / 2;
10+
int r = mid / n;
11+
int c = mid % n;
12+
if (matrix[r][c] == target) {
13+
return true;
14+
} else if (matrix[r][c] > target) {
15+
right = mid - 1;
16+
} else {
17+
left = mid + 1;
18+
}
19+
}
20+
return false;
21+
}
22+
}

0 commit comments

Comments
 (0)