求问二分是否有问题,最后一个节点超时
查看原帖
求问二分是否有问题,最后一个节点超时
1233805
zhaowufangnai楼主2024/3/7 23:21
#include<bits/stdc++.h>
using namespace std;
const int v = 1000010;
int a[v];
int num(int y,int z)
{
	int left = 0;
	int right = y;
	
	while (left <= right)
	{
		int middle = (left+right) / 2;
		if (a[middle] < z)
			left = middle + 1;
		else if (a[middle] > z)
			right = middle - 1;
		else if (a[middle] == z)
		{
			return middle;
			break;
		}
	}
	if (left > right)
		return -1;

}

int main()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout.tie(0);
	int num( int y,int z);
	int n = 0, m = 0;
	cin >> n >> m;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	for (int i = 0; i < m; i++)
	{
		int temp;
		cin >> temp;
		int x = num(n-1,temp);
		if (x == -1)
			cout << x << " ";
		else if (x == 0)
			cout << 1 << " ";
		else
		{
			int i = 0;
            for ( i = x-1;i>=0; i--)
		     {
				if (a[i] != a[x])
				{
					x = i + 1;
					break;
				}
		     }
	_ _ _ 
		cout << x+1<<" ";
		}
		
	}
	return 0;
}
2024/3/7 23:21
加载中...