BlueTiger @ 2023-01-30 21:17:45
#include<iostream>
using namespace std;
int nums[100100100],n,m,ans;
int search(int target){
int left=0;
int right=n-1;
while(left<=right){
int middle=(left+right)/2;
if(nums[middle]>target) right=middle-1;
else if(nums[middle]<target) left=middle+1;
else return middle;
}
return -1;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>nums[i];
for(int i=1;i<=m;i++){
int target;
cin>>target;
int ans=search(target);
cout<<ans<<" ";
}
cout<<endl;
return 0;
}
by gghack_Nythix @ 2023-01-30 21:20:10
可以用lower_bound
by BlueTiger @ 2023-01-30 21:22:08
@gghack_m3d
能手打我尽量不用lower_bound
by Accelessar @ 2023-01-30 21:25:49
left 设为 1,right 设为 n,因为你的数组是从 1 开始编号的。
by BlueTiger @ 2023-01-30 21:31:40
@AZN_0975 照错不误.
by Accelessar @ 2023-01-30 21:35:53
@BlueTiger 帮您改了一下
int search(int target){
int left=1;
int right=n;
while(left<=right){
int middle=(left+right)/2;
if(nums[middle]>=target) right=middle-1;
else left=middle+1;
}
return nums[left]==target?left:-1;
}
by gghack_Nythix @ 2023-01-30 21:37:29
@BlueTiger 过了
#include<iostream>
using namespace std;
int nums[100100100],n,m,ans;
int search(int target){
int left=1,ans = 0;
int right=n;
while(left<=right){
int middle=(left+right)/2;
if(nums[middle]>=target) //第一个错的{right=middle-1;ans = middle;//记录一下ans,有可能是答案}
else left = middle + 1;
}
if(nums[ans] == target){//验证
return ans;
}
return -1;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>nums[i];
for(int i=1;i<=m;i++){
int target;
cin>>target;
int ans=search(target);
cout<<ans<<" ";
}
cout<<endl;
return 0;
}
by BlueTiger @ 2023-02-01 20:46:33
@gghack_m3d @AZN_0975 谢谢大佬,过了
by Do_www @ 2023-02-01 21:14:17
@AZN_0975 佬,这题数组从0开始为啥过不去啊
by Accelessar @ 2023-02-01 21:25:22
@wry_123 最后输出时要将 l 加 1,因为题目问的编号是从 1 开始的编号。