Created
March 6, 2013 05:58
-
-
Save daifu/5097063 to your computer and use it in GitHub Desktop.
Given a sorted integer array and a key, output its indices’ range.
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 integer array and a key, output its indices’ range. | |
| For example, | |
| [5, 7, 7, 8, 8, 10] –> Given 8, outputs [3, 4] | |
| */ | |
| public class Untitled { | |
| // get a range of position of sorted array | |
| public int[] getRange(int[] input, int target) { | |
| int upper = getUpperBound(input, target); | |
| int lower = getLowerBound(input, target); | |
| int[] ret = new int[2]; | |
| ret[0] = lower; | |
| ret[1] = upper; | |
| return ret; | |
| } | |
| // search upperbound of repeated target | |
| public int getUpperBound(int[] input, int target) { | |
| double left = 0; | |
| double right = input.length - 1; | |
| while(right >= left) { | |
| int mid = (int)Math.ceil((left + right)/2); | |
| if(input[mid] < target) { | |
| left = mid + 1; | |
| } else if(input[mid] > target) { | |
| right = mid - 1; | |
| } else { | |
| if(right != mid) { | |
| left = mid; | |
| } else { | |
| return mid; | |
| } | |
| } | |
| } | |
| return -1; | |
| } | |
| // search lowerbound of repeated target | |
| public int getLowerBound(int[] input, int target) { | |
| double left = 0; | |
| double right = input.length - 1; | |
| while(right >= left) { | |
| int mid = (int)Math.floor((left + right)/2.0); | |
| if(input[mid] < target) { | |
| left = mid + 1; | |
| } else if(input[mid] > target) { | |
| right = mid - 1; | |
| } else { | |
| if(left != mid) { | |
| right = mid; | |
| } else { | |
| return mid; | |
| } | |
| } | |
| } | |
| return -1; | |
| } | |
| public static void main(String[] args) { | |
| // Start typing your code here... | |
| System.out.println("Hello world!"); | |
| int[] testInput = {5,7,7,8,8,8,8,8,10}; | |
| Untitled test = new Untitled(); | |
| int[] res = test.getRange(testInput, 4); | |
| System.out.println(res[0]); | |
| System.out.println(res[1]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment