6 条题解

  • 3
    @ 2026-10-4 10:02:26

    不使用lower_bound函数

    #include <bits/stdc++.h>
    #define int long long
    using namespace std;
    const int INF = 0x3f3f3f3f;
    const int N = 1e5 + 10;
    int n , m , cnt , a [N];
    signed main()
    {
    		cin >> n >> m;
    		for (int i = 1; i <= n; i++) cin >> a [i];
    		while ( m-- )
    		{
    			cin >> cnt;
                int l = 1 , r = n , ans = INF;
                while (l <= r)
                {
                    int mid = l + r >> 1;
                    if (cnt <= a [mid])//要查找的值小于当前值
                    {
                        if (a [mid] == cnt)
                            ans = min (ans , mid);
                        r = mid - 1;
                    } 
                    else l = mid + 1;
                }
                if (ans == INF) cout << "-1\n";
                else cout << ans << "\n";
    		}
    		return 0;
    }
    
    

    使用lower_bound函数

    #include <bits/stdc++.h>
    #define int long long
    using namespace std;
    const int INF = 0x3f3f3f3f;
    const int N = 1e5 + 10;
    int n , m , cnt , a [N];
    signed main()
    {
    		cin >> n >> m;
    		for (int i = 1; i <= n; i++) cin >> a [i];
    		while ( m-- )
    		{
    			cin >> cnt;
                if (a [lower_bound (a + 1 , a + n + 1 , cnt) - a]!= cnt) cout << "-1\n";
    		    else cout << (lower_bound (a + 1 , a + n + 1 , cnt) - a) << "\n";
    		}
    		return 0;
    }
    
    
    

    信息

    ID
    3098
    时间
    1000ms
    内存
    256MiB
    难度
    2
    标签
    递交数
    147
    已通过
    40
    上传者