Skip to content

Commit

Permalink
added alternative solution to GuessNumberHigherOrLower.java
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevin Naughton Jr authored and Kevin Naughton Jr committed Jun 4, 2018
1 parent fbbb6db commit 3d5dc11
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 51 deletions.
35 changes: 12 additions & 23 deletions company/google/GuessNumberHigherOrLower.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,19 @@

public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
return binarySearch(1, n);
}

private int binarySearch(int start, int end) {
if(start > end) {
return -1;
}

if(guess(start) == 0) {
return start;
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}

if(guess(end) == 0) {
return end;
}

int mid = start + (end - start) / 2;

if(guess(mid) == 0) {
return mid;
} else if(guess(mid) == 1) {
return binarySearch(mid + 1, end);
} else {
return binarySearch(start, mid - 1);
}
return -1;
}
}
40 changes: 12 additions & 28 deletions leetcode/binary-search/GuessNumberHigherOrLower.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,21 @@

// Return 6.

/* The guess API is defined in the parent class GuessGame.
@param num, your guess
@return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num); */

public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
return binarySearch(1, n);
}

private int binarySearch(int start, int end) {
if(start > end) {
return -1;
}

if(guess(start) == 0) {
return start;
}

if(guess(end) == 0) {
return end;
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}

int mid = start + (end - start) / 2;

if(guess(mid) == 0) {
return mid;
} else if(guess(mid) == 1) {
return binarySearch(mid + 1, end);
} else {
return binarySearch(start, mid - 1);
}
return -1;
}
}

0 comments on commit 3d5dc11

Please sign in to comment.