转自: http://www.careercup.com/question?id=5129701993480192
Given an array of ages (integers) sorted lowest to highest, output the number of occurrences for each age.
For instance:[8,8,8,9,9,11,15,16,16,16]
should output something like:
8: 3
9: 2
11: 1
15: 1
16: 3
This should be done in less than O(n).
This problem can be solved in less than O(n) using a modified binary search.
For each element in the array ages[] (starting from 0) we record the first index i where this age is present, then we search using binary search the last index where this age is present.
The number of people with the same age will be given by lastindex-firstindex for this age.
Then we retake the search from lastindex+1 for the next age.
1+(lastindex-startindex) to get the number of people with the same age for each key in the map.
public static Map<Integer,Integer> countAges(int[] ages) {
if(ages==null || ages.length==0) {
return new HashMap<Integer,Integer>();
}
int i = 0;
int end = 0;
Map<Integer,Integer> count = new HashMap<Integer,Integer>();
int from = 0;
int to = 0;
while(i<ages.length) {
from = i;
end=binSearchEnd(ages,i,ages.length);
to = end;
count.put(ages[i], 1+to-from);
i=end+1;
}
return count;
}
and this is the method to search for the last index of an age in the array of ages using binary search:
public static int binSearchEnd(int[] ages, int start, int end) {
if(start+1>ages.length-1 || ages[start]!=ages[start+1]) return start;
if(ages[start]==ages[ages.length-1]) return ages.length-1;
int i = start+1;
int k = ages[start];
while(start<i && i+1<ages.length) {
//System.out.println("i: "+i);
if(ages[i]==k && ages[i+1]!=k) return i;
else if(ages[i]>k) {
end=i;
i=(start+i)/2;
}
else { //ages[i]==k && ages[i+1]==k
start=i;
i=(i+end)/2;
}
if(i>=ages.length-1) return i;
}
return i;
}