Given an array of ages (integers) sorted lowest to highest, output the number of occurrences for eac

43 篇文章 0 订阅

转自: 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;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值