#include <cstdio> #include <iostream> #include <string> using namespace std; int n,m; int find(int a[1000000],int num){ int count = 0; int left = 0; int right = n - 1; while(true){ if(a[left] == num){ return left; } if(a[right] == num){ return right; } if(a[(left+right)/2] > num){ right = (left + right)/2; } if(a[(left+right)/2] < num){ left = (left + right)/2; } if(a[(left+right)/2] == num){ count = (left+right)/2; break; } if(left == right - 1||left == right){ return -2; } } while((a[count - 1])==num){ count--; } return count; } int main(){ int a[1000000]; int b[100000]; cin >> n >> m; for(int i = 0;i < n;i++){ cin >> a[i]; } for(int i = 0;i < m;i++){ cin >> b[i]; } for(int i = 0;i < m;i++){ cout << find(a,b[i])+1 << " "; } }
算法初步P1.二分查找
最新推荐文章于 2024-11-08 23:36:48 发布