正常遍历会超时,用二分法简单且快
二分就是划定,然后不断更新左或右两个边界
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int x;
cin >> x;
vector<int> shop(x);
for (int i = 0; i < x; i++)
cin >> shop[i];
int n;
cin >>n;
vector<int> money(n);
for (int i = 0; i < n; i++)
cin >> money[i];
vector<int> result(n,0);
sort(shop.begin(), shop.end());//升序排列
//二分
for (int i = 0; i < n; i++)
{
int cost = money[i];
int count = 0;
int left = 0, right = x - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (shop[mid] <= cost)
{
count = mid + 1;
left = mid + 1;
}
else
right = mid - 1;
}
result[i] = count;
}
/*正常排序超时了
for (int i = 0; i < n; i++)
{
for (int j = 0; j < x; j++)
{
if (money[i] >= shop[j])
result[i]++;
}
}
*/
for (int& i:result)
{
cout << i << endl;
}
cin.get();
}