jayati

Find First and Last Position of Element in Sorted Array

Mar 11th, 2023
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> searchRange(vector<int>& nums, int target) {
  4.         int start=0;
  5.         int end = nums.size()-1;
  6.         vector<int> v;
  7.         int c=0;
  8.         int c1=0;
  9.         bool f = false;
  10.         while(start<=end)
  11.         {
  12.             if(nums[start]==target && c==0)
  13.             {
  14.                 v.push_back(start);
  15.                 c++;
  16.             }
  17.             if(nums[end]==target && c1==0)
  18.             {
  19.                 if(c==0)
  20.                 {
  21.                     f=true;
  22.                 }
  23.                 v.push_back(end);
  24.                 c1++;
  25.             }
  26.             if(c==1 && c1==0)
  27.             {
  28.                 end--;
  29.             }
  30.             else if(c==0 && c1==1)
  31.             {
  32.                 start++;
  33.             }
  34.             else if(c==0 && c1==0)
  35.             {
  36.                 start++;
  37.                 end--;
  38.             }
  39.             else
  40.             {
  41.                 break;
  42.             }
  43.            
  44.         }
  45.         if(v.size()==0)
  46.         {
  47.             v.push_back(-1);
  48.             v.push_back(-1);
  49.         }
  50.         if(f)
  51.         {
  52.           reverse(v.begin(), v.end());
  53.         }
  54.        
  55.         return v;
  56.     }
  57. };
Advertisement
Add Comment
Please, Sign In to add comment