Yemuua @ 2023-11-28 22:17:09
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int* a;
int* b;
int n;
int qs(int start, int end, int t) {
int l = start, r = end;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] < t) {
l = mid + 1;
}
else if (a[mid] > t) {
r = mid - 1;
}
else {
while (a[mid - 1] == t && mid >= 1) {
mid--;
}
return mid;
}
}
if (l > r) {
return -1;
}
}
int main(){
int m;
scanf_s("%d%d", &n, &m);
a = (int*)malloc(n * sizeof(int));
b = (int*)malloc(m * sizeof(int));
for (int i = 0; i < n; i++) {
scanf_s("%d", a + i);
}
for (int i = 0; i < m; i++) {
scanf_s("%d", b + i);
int x = qs(0, n - 1, b[i]);
if (x == -1) {
printf("%d ", -1);
}
else {
printf("%d ", x + 1);
}
}
free(a);
free(b);
return 0;
}
是搜索部分还要再改吗?
by __yun__ @ 2023-11-28 22:32:15
搜索部分中else那部分太暴力了,会超时。
by __yun__ @ 2023-11-28 22:39:06
贴份代码你自已看看吧。
#include<bits/stdc++.h>
using namespace std;
const int M=1e6+10;
int n,m,a[M];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int x;
while(m--){
cin>>x;
int l=1,r=n,mid;
while(l<=r){
mid=(l+r)/2;
if(a[mid]<x) l=mid+1;
else r=mid-1;
}
//l是第一个大于等于查询数字的数的下表
if(a[l]!=x) cout<<-1<<" ";
else cout<<l<<" ";
}
return 0;
}
by Yemuua @ 2023-11-28 22:45:08
@yun 原来是这部分暴力了吗?有点没想到
by Yemuua @ 2023-11-28 22:54:25
@yun 多谢,我看懂了,但是做的时候没想到把右边界一直压缩,然后把l给赶到查找的数k的位置上这种方法。