#include <stdio.h> #define N 100010 int n, q; int array[N]; // N的范围来确定数组开的范围(0,n],开的范围要比n大,10 // 第一次出现位置 int num_1(int q[], int len, int x) { int l = -1, r = len; while (l + 1 < r) { int mid = (l + r) / 2; if (q[mid] < x) { l = mid; } else { r = mid; } } if (q[r] == x) return r; else return -1; } // 第二次出现位置 int num_2(int q[], int len, int x) { int l = -1, r = len; while (l + 1 < r) { int mid = (l + r) / 2; if (q[mid] <= x) { l = mid; } else { r = mid; } } if (q[l] == x) return l; else return -1; } int main() { scanf("%d %d", &n, &q); for (int i = 0; i < n; i++) { scanf("%d", &array[i]); } while (q--) { int x; scanf("%d", &x); int res1 = num_1(array, n, x); int res2 = num_2(array, n, x); printf("%d %d\n", res1, res2); } return 0; } /*输入: 6 3 1 2 2 3 3 4 3 4 5 */ /*输出: 3 4 5 5 -1 -1 */
标签:二分,num,int,mid,len,else,while,查找 From: https://www.cnblogs.com/gjkt2001/p/17279240.html