求大佬解答一下
查看原帖
求大佬解答一下
1356325
Besokus楼主2024/11/22 15:46

求大佬解答一下,为什么RE,用了二分法时间复杂度没这么大啊

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdio> 
#include<algorithm>

using namespace std;

struct Num {
	long id, data;
};

void erfen(struct Num a[], int size, long target) {
	int l = 0, r = size, mid = (l + r) / 2;
	int index = 0;
	while (l <= r) {
		mid = (l + r) / 2;
		if (target < a[mid].data) {
			r = mid - 1;
		}
		else if (target > a[mid].data) {
			l = mid + 1;
		}
		else 
			if (mid == 0) {
				printf("%d ", a[mid].id);
				return;
			}
			else {//查看前面有没有和mid相同的,找到第一个
				for (int j = mid; j > 0; j--) {
					if (a[j].data == a[mid].data && j != 0) {
						continue;
					}

					else {
						printf("%d ", a[j + 1].id);
						return;
					}
				}
			}
		}
	
	printf("-1 ");
}

int main() {
	int n, m, x;
	Num s[100005] = {0};
	scanf("%d %d", &n, &m);
	//vector<Num>a;
	vector<long long>b;
	int i;
	for (i = 0; i < n; i++) {
		scanf("%d", &x);
		s[i].data = x;
		s[i].id = i + 1;
		//a.push_back(s[i]);
	}
	for (int j = 0; j < m; j++) {
		scanf("%d", &x);
		b.push_back(x);
	}


	for (int k = 0; k < b.size(); k++) {
		erfen(s, i, b[k]);
	}

	return 0;
}
2024/11/22 15:46
加载中...