双指针问题

codeforces:Queries about less or equal elements

You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

Input
The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b.

The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109).

The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Output
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

Examples
inputCopy
5 4
1 3 5 7 9
6 4 2 8
outputCopy
3 2 1 4
inputCopy
5 5
1 2 1 2 5
3 1 4 1 5
outputCopy
4 2 4 2 5

双指针问题,遍历一个,另一个要注意限制,限制j<=n,如果j>n,就break掉。

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=2e5+5;
struct node
{
	int id;
	int zhi;
	int shu;
}b[N];
int a[N];
bool cmp(node x,node y)
{
	return x.zhi<y.zhi;
}
bool cmp1(node x,node y)
{
	return x.id<y.id;
}
int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	for(int i=1;i<=m;i++)
	{
		cin>>b[i].zhi;
		b[i].id=i;
		b[i].shu=0;
	}
	sort(b+1,b+1+m,cmp);
	int j=1;
	for(int i=1;i<=m;i++)
	{
		b[i].shu=b[i-1].shu;
		while(b[i].zhi>=a[j]&&j<=n)
		{
			b[i].shu=j;
			j++;
			if(j>n){
				break;
			}
		}
		
	}
	sort(b+1,b+1+m,cmp1);
	for(int i=1;i<=m;i++)
	{
		cout<<b[i].shu<<" ";
	}
	
	
	return 0;
} ```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值