From 124d62ceeeabdc37a653a81d12a3f1d059da1be2 Mon Sep 17 00:00:00 2001 From: Avani Mathur <151984867+avanimathur@users.noreply.github.com> Date: Sat, 27 Jan 2024 18:00:28 +0530 Subject: [PATCH] Day 26 q3 --- .../avanimathur--C.cpp | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Day-26/q3: Find first and last position of element in sorted array/avanimathur--C.cpp diff --git a/Day-26/q3: Find first and last position of element in sorted array/avanimathur--C.cpp b/Day-26/q3: Find first and last position of element in sorted array/avanimathur--C.cpp new file mode 100644 index 00000000..a35d9884 --- /dev/null +++ b/Day-26/q3: Find first and last position of element in sorted array/avanimathur--C.cpp @@ -0,0 +1,72 @@ +#include +using namespace std; + +class Solution { + +public: + + int firstfind(vector nums, int n, int target){ + + int firstOc = -1; + int low = 0 , high = n -1 ; + + while ( low <= high ){ + + int mid = ( low + high ) / 2; + + if ( target == nums[mid]){ + firstOc = mid ; + high = mid - 1 ; + } + + else if ( target > nums[mid]){ + low = mid + 1; + } + + else{ + high = mid - 1; + } + } + + return firstOc; + + } + + int lastfind(vector nums, int n,int target){ + + int lastOc = -1 ; + int low = 0 , high = n -1 ; + + while ( low <= high ){ + + int mid = ( low + high ) / 2; + + if ( target == nums[mid]){ + lastOc = mid ; + low = mid + 1 ; + } + + else if ( target > nums[mid]){ + low = mid + 1; + } + + else { + high = mid - 1; + } + } + + return lastOc; + + } + + vector searchRange(vector& nums, int target) { + + int n = nums.size() ; + int firstOccur = firstfind(nums,n,target) ; + int lastOccur = lastfind(nums,n,target) ; + + return {firstOccur,lastOccur}; + + } + +}; \ No newline at end of file