Number range - Second

Given a length in ascending order of an array of integers n, and q queries.

For each query, a return element k start and end positions (position counting from 0).

If the element is not present in the array, "-1-1" is returned.

Input format
The first line contains integers n and q, and the array length represents the number of interrogation.

The second line contains n integers (both in the range of 1 to 10,000) indicating the full array.

Next q rows, each row contains an integer k, represents a query element.

Output format
co q rows, each row comprising two integers representing the start and end positions of the elements required.

If the element is not present in the array, "-1-1" is returned.

Data range
1≤n≤100000
1≤q≤10000
1≤k≤10000
Input Sample:
. 6. 3
. 1. 4. 3. 3 2 2
. 3
. 4
. 5
Output Sample:
. 3. 4
. 5. 5
-1 -1

Note: Find the first occurrence and is worth half of the last occurrence of different

#include <iostream>
using namespace std;

int n,q,k;
int a[100005];

int main(){
	cin >> n >> q;
	for(int i = 0; i < n; i++){
		cin >> a[i];
	}
	for(int i = 0; i < q; i++){
		int t; cin >> t;
		int l = 0, r = n - 1;
		while( l < r){
			int mid = (l + r)  / 2;
			//cout << "l = " << l << " r  =" << r << " mid = " << mid << endl;
			if(a[mid] >= t){
				r = mid;
			}else{
				l = mid + 1;
			}
		}
		//cout << "l = " << l << " r = " << r << endl;
		if(a[l] != t){
			cout << "-1 -1" << endl;
		}else{
			cout << l << " ";
			int l  = 0, r = n - 1;
			while(l < r){
				int mid = l + r + 1 >> 1;
				if(a[mid] <= t) l = mid;
				else r = mid - 1; 
			}
			cout << l << endl;
		}
	}	
	return 0;
}





/*
6 3
1 2 2 3 3 4
3
4
5
*/

Published 11 original articles · won praise 0 · Views 120

Guess you like

Origin blog.csdn.net/qq_41581913/article/details/104093631