Created
March 22, 2015 19:40
-
-
Save nikoncode/8411e7fbcb386cad8c18 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
| public static void main(String[] args) { | |
| AbstractPurchase purchases[] = {...}; | |
| Arrays.sort(purchases); | |
| print(purchases); | |
| /* http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(byte[],%20byte) | |
| * binarySearch return index of the search key, if it is contained in the array; | |
| * otherwise, (-(insertion point) - 1). Use it by create comparator without return 0 | |
| * (equals) section. binarySearch with this comparator always return insertion point. | |
| */ | |
| final long SEARCH_COST = 90000; | |
| Comparator<AbstractPurchase> comp = new Comparator<AbstractPurchase>() { | |
| @Override | |
| public int compare(AbstractPurchase o1, AbstractPurchase o2) { | |
| if (o1.getCost() > SEARCH_COST) { | |
| return -1; | |
| } | |
| return 1; | |
| } | |
| }; | |
| int f = Arrays.binarySearch(purchases, null, comp); | |
| /* Insertion point reverse transformation */ | |
| f = -f - 1; | |
| if (f < purchases.length && purchases[f].getCost() == SEARCH_COST) { | |
| int l = f + 1; | |
| while (l < purchases.length && purchases[l].getCost() == SEARCH_COST) { | |
| l++; | |
| } | |
| System.out.printf("[%d,%d)", f, l); | |
| } else { | |
| System.out.println("NOT FOUND"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment