/**
* 找找第k个数在第几堆里,例如:
* int k = 25;
* int[] array = new int[]{10, 12, 14, 15};
* 答案是 3 .
*
* @param heaps
* @param k
* @return
*/
public static int whereAmI(int[] heaps, int k) {
if (null == heaps || 0 == heaps.length || 0 >= k) {
return -1;
}
int[] heapRecord = new int[heaps.length];
int sum = 0;
for (int i = 0; i < heaps.length; i++) {
sum += heaps[i];
heapRecord[i] = sum;
}
if (k > sum) {
return -1;
}
return 1 + whereAmI(heapRecord, 0, heaps.length - 1, k);
}
private static int whereAmI(int[] heapRecord, int start, int end, int k) {
if (start >= end) {
return start;
}
int mid = start + (end - start) / 2;
if (heapRecord[mid] == k) {
return mid;
}
if (heapRecord[mid] < k) {
return whereAmI(heapRecord, mid + 1, end, k);
}
return whereAmI(heapRecord, start, mid - 1, k);
}