Skip to content

Commit 1d3f1d4

Browse files
committed
[Function add]
1. Add leetcode solutions with tag binary search.
1 parent fe9736c commit 1d3f1d4

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

leetcode/378. Kth Smallest Element in a Sorted Matrix.md

Whitespace-only changes.

leetcode/69. Sqrt(x).md

+18
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,21 @@ class Solution {
6666
}
6767
}
6868
```
69+
70+
71+
### Third Time
72+
* Method 1: binary search
73+
```Java
74+
class Solution {
75+
public int mySqrt(int x) {
76+
if(x == 0 || x == 1) return x;
77+
int left = 1, right = x / 2;
78+
while(left <= right){
79+
int mid = left + (right - left) / 2;
80+
if(mid > x / mid) right = mid - 1;
81+
else left = mid + 1;
82+
}
83+
return right;
84+
}
85+
}
86+
```

leetcode/74. Search a 2D Matrix.md

+23
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,26 @@ class Solution {
5959
}
6060
}
6161
```
62+
63+
### Third Time
64+
* Method 1: Binary Search, AC 100%
65+
```Java
66+
class Solution {
67+
public boolean searchMatrix(int[][] matrix, int target) {
68+
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
69+
int height = matrix.length, width = matrix[0].length;
70+
int row = 0;
71+
while(row < height && target > matrix[row][width - 1]){
72+
row++;
73+
}
74+
return row >= height ? false: bs(matrix[row], 0, width - 1, target);
75+
}
76+
private boolean bs(int[] nums, int low, int high, int target){
77+
if(low > high) return false;
78+
int mid = low + (high - low) / 2;
79+
if(target == nums[mid]) return true;
80+
else if(target > nums[mid]) return bs(nums, mid + 1, high, target);
81+
else return bs(nums, low, mid - 1, target);
82+
}
83+
}
84+
```

0 commit comments

Comments
 (0)