[Google]maximum n such that the array consists at least n values >=n

Question:

Given an unsorted array of integers, you need to return maximum possible n such that the array consists at least n values greater than or equals to n. Array can contain duplicate values. 

Sample input : [1, 2, 3, 4] -- output : 2 

Sample input : [900, 2, 901, 3, 1000] -- output: 3


Solution:

有两种思路:

1.假设数组大小为m,要找n,那么n<=m,对数组元素x做以下处理

1)x<=0,不考虑,因为x对n的选择不影响

2)x>=m 当做m考虑,因为不存在n>m.

程序如下:

public int findMaxN(int[] array)
	{
		int len=array.length;
		int[] count=new int[len+1];
		for(int i=0;i<len;i++)//统计每个数出现的个数.需要对数字做一些处理
		{
			if(array[i]<=0) continue;
			else if(array[i]>=len)count[len]++;
			else count[ array[i] ]++;
		}
		int mn=0;
		for(int i=count.length-1;i>-1;i--)
		{
			mn+=count[i];//把大于等于i的数都加起来
			if(mn>=i)return i;
		}
		return 0;
	}

2.对n进行猜测,开始假设n=m/2,然后将数组排序,大于array[m/2]的排左边,小于array[m/2]的排右边,那么现在保证0,1,...,m/2-1的值都大于array[m/2], m/2+1,m/2+2,...,m-1都小于array[m/2],比较array[m/2]与n,如果array[m/2]>=n,那么寻找的n肯定在数组右边,否则n在数组左边.

代码如下:

int Solve( std::vector<int> &arr ){
	int m = arr.size(), max = 0;
	for( int low = 0, high = arr.size(); low < high; ){
		int n = (low+high)/2;
		std::nth_element( arr.begin()+low, arr.begin()+n, arr.begin()+high,
			[](const int &a, const int &b){ return a>b; } );

		//now arr[0..n-1] >= arr[n], arr[n+1...] <= arr[n]
		if( arr[n] >= n+1 ){
			max = std::max( max, n+1 );
			low = n+1;
		}
		else {
			high = n;
		}
	}
	return max;	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值