Last active
December 14, 2015 09:59
-
-
Save charlespunk/5068606 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Given a sorted array of strings which is interepersed with empty strings, write a method to find the location of a given string. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int findLocation(int begin, int end, String input, String[] array){ | |
if(begin > end) return -1; | |
int mid = (begin + end) / 2; | |
int leftEnd = mid - 1; | |
int rightBegin = mid + 1; | |
if(array[mid] == ""){ | |
while(true){ | |
if(leftEnd < 0 && rightBegin >= array.length) return -1; | |
else if(leftEnd >= 0 && array[leftEnd] != ""){ | |
mid = leftEnd; | |
leftEnd--; | |
break; | |
} | |
else if(rightBegin < array.length && array[rightBegin] != ""){ | |
mid = rightBegin; | |
rightBegin++; | |
break; | |
} | |
leftEnd--; | |
rightBegin++; | |
} | |
} | |
if(array[mid].equals(input)) return mid; | |
int num = findLocation(begin, leftEnd, input, array); | |
if(num == -1) num = findLocation(rightBegin, end, input, array); | |
return num; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment