Advertisement
Niloy007

First and last occurrences of x

Mar 14th, 2021
1,129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. // { Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. vector<int> find(int a[], int n , int x );
  5.  
  6. int main()
  7. {
  8.     int t;
  9.     cin>>t;
  10.     while(t--)
  11.     {
  12.         int n,x;
  13.         cin>>n>>x;
  14.         int arr[n],i;
  15.         for(i=0;i<n;i++)
  16.         cin>>arr[i];
  17.         vector<int> ans;
  18.         ans=find(arr,n,x);
  19.         cout<<ans[0]<<" "<<ans[1]<<endl;
  20.     }
  21.     return 0;
  22. }
  23.  
  24.  
  25. // } Driver Code Ends
  26.  
  27.  
  28. vector<int> find(int arr[], int n , int x )
  29. {
  30.     // code here
  31.     int lo = lower_bound(arr, arr + n, x) - arr;
  32.     int up = upper_bound(arr, arr + n, x) - arr;
  33.     vector<int> v;
  34.     if (lo == n) {
  35.         v.push_back(-1);
  36.         v.push_back(-1);
  37.         return v;
  38.     }
  39.     if (arr[lo] != x) {
  40.         v.push_back(-1);
  41.         v.push_back(-1);
  42.         return v;
  43.     }
  44.     v.push_back(lo);
  45.     v.push_back(up - 1);
  46.     return v;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement