Skip to content

Commit 8c4f27d

Browse files
committed
GuessNumberHigherorLower
1 parent 01d92bc commit 8c4f27d

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
public class Solution extends GuessGame {
2+
public int guessNumber(int n) {
3+
int left = 1;
4+
int right = n;
5+
return helper(n, left, right);
6+
}
7+
private int helper(int n, int left, int right){
8+
if(left > right) return -1;
9+
int mid = left + (right - left) / 2;
10+
if(guess(mid) == 0) return mid;
11+
if(guess(mid) == -1) return helper(n, left, mid - 1);
12+
else return helper(n, mid + 1, right);
13+
}
14+
}

(#704)BinarySearch/BinarySearch.java

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

0 commit comments

Comments
 (0)