求调

P2249 【深基13.例1】查找

xiao_liran @ 2024-06-22 18:48:32


using namespace std;
int a[1000005];
int erfen(int n,int key){
    int left=1,right=n,mid;
    while(left<=right){
        mid=(left+right)/2;
        if(a[mid]==key) return mid;
        else if(a[mid]>key) right=mid-1;
        else left=mid+1;
    }
    return 0;
}
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    } 
    while(cin>>m){
        int da=erfen(n,m);//cout<<"fdefwfwefgwe"<<"   "; 
        if(da!=0) cout<<da<<endl;
        else cout<<-1<<endl; 
    }
    return 0;
}
P2249 谢谢

by Fish_Love_Water @ 2024-06-22 20:23:39

@xiao_liran erfen函数里面要把

return 0;

改为

if (a[l]==num) return l; 
else return -1; 

求关


by Fish_Love_Water @ 2024-06-22 20:24:26

@Fish_Love_Water 抱歉,是

if (a[l]==key) return l; 
else return -1; 

by keep_shining @ 2024-06-22 20:27:36

@xiao_liran 题目不是让你求 m 个数吗?你搁着 while(cin>>m) 干啥?


by keep_shining @ 2024-06-22 20:29:01

@xiao_liran 你这 m 前边输入了,后边就写 while(m--) 来读入这 m 个数,别忘了里面读入的变量要改个名


by keep_shining @ 2024-06-22 20:30:59

@xiao_liran 还有,题目是求第一次出现的位置,你不能找到就停止,说不定前面还有呢


by lix_qaq @ 2024-07-07 15:07:00

可能出现多个相同数据,所以二分找到一个后还要继续判定,不能直接return

样例不都有吗?

这题主要易错点就在这了:D

#include <bits/stdc++.h>
using namespace std;
int a[1000005];
int erfen(int n,int key){
    int left=1,right=n,mid,ans=-1;
    while(left<=right){
        mid=(left+right)/2;
        if(a[mid]==key){
            //主要这里改了:) 
            ans=mid;
            right=mid-1;
        }
        else if(a[mid]>key) right=mid-1;
        else left=mid+1;
    }
    return ans;
}
int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    } 
    while(cin>>m){
        cout<<erfen(n,m)<<" ";//cout<<"fdefwfwefgwe"<<"   ";
        //输出可以简单点,不用那么复杂:D 
    }
    return 0;
}

|