From ea4dc161d85beb25fe2c45e7217b11c6a7a3baa9 Mon Sep 17 00:00:00 2001 From: Km Pooja Date: Fri, 8 Oct 2021 16:13:19 +0530 Subject: [PATCH] Find first and last occur --- HacktoberFest2021/C++ Programs/findOccur.cpp | 77 ++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 HacktoberFest2021/C++ Programs/findOccur.cpp diff --git a/HacktoberFest2021/C++ Programs/findOccur.cpp b/HacktoberFest2021/C++ Programs/findOccur.cpp new file mode 100644 index 0000000..ac143fb --- /dev/null +++ b/HacktoberFest2021/C++ Programs/findOccur.cpp @@ -0,0 +1,77 @@ +#include +#include + +/* Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. + +If target is not found in the array, return [-1, -1]. + +You must write an algorithm with O(log n) runtime complexity. + + +Example 1: +Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] + +Example 2: +Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] + +Example 3: +Input: nums = [], target = 0 +Output: [-1,-1] +*/ + +//time complexity O(logn) +using namespace std; +int firstOccur(int arr[],int n,int target){ + int lo=0; + int hi=n-1; + int mid=0; + int result=-1; + while(lo<=hi){ + mid=lo+(hi-lo)/n; + if(arr[mid]==target){ + result=mid; + hi=mid-1; + } + else if(arr[mid]>n; + int arr[n]; + cout<<"Enter elements in array"<>arr[i]; + int target; + cout<<"Enter the target value"<>target; + int first =firstOccur(arr,n,target); + int last=lastOccur(arr,n,target); + cout<