Peak Index in a Mountain Array || Binary Search practice example || Leet Code poblem #852
|| Peak Index in a Mountain Array
|| Binary Search practice example
|| Leet Code poblem #852
Given an integer array arr we have to return the index of peak element.
Array first increase and then decrease.
Format a[1] < a[2] < a[3] <........a[n].......> a[2] > a[1]
We have to return the index of a[n]
Input: arr = [0,1,0] Output: 1
Input: arr = [0,2,1,0] Output: 1Input: arr = [0,10,5,2] Output: 1***************CODE****************//TIME COMPLEXITY IS O(LOG N)
int peakIndexInMountainArray(vector<int>& arr) {
int s=0;
int e=arr.size()-1;
int mid= s + (e-s)/2;
while (s<e){
if(arr[mid] < arr[mid+1]){
s = mid +1;
}
else
e= mid;
mid= s + (e-s)/2;
}
return s;
}
Nice 😁
ReplyDelete😀👍
Delete