Find a Peak Element in an Array | LeetCode 162 | Programming Tutorials

preview_player
Показать описание
Given an array of integers, find a peak element. The array may contain multiple peak elements, in that case return any one peak element.

A peak element is an element which is greater than it's neighbours.

In this tutorial, I have discussed how we can find a peak element using linear scan and a binary search using java code.

Interview questions on an array -
Рекомендации по теме
Комментарии
Автор

Code link is present in the description box.

ProgrammingTutorialsM
Автор

Will it work in this case array = [1, 2, 1, 4, 5, 6, 7, 8, 9, 10], here the peak is 2, but the above code logic will fail.

arunks
Автор

But if it is not sorted order then it will not work i.e binary search

sureshpathak
Автор

Great Explaination!
Could you please explain why does exactly your code works and not this with the minor change which seems equivalent to your code:

class Solution {
public int findPeakElement(int[] nums) {
int l=0, h=nums.length-1;

while(l<=h) {
int m= l+(h-l)/2;
if((m==0 || nums[m-1]<nums[m]) && (m==nums.length-1 || nums[m]>nums[m+1]))
return m;
else if(m>0 && nums[m-1]<nums[m])
l=m+1;
else h=m-1;
}
return -1;
}
}

PRiyankaSingh-nddn
Автор

if we use this array:
int [ ] arr= {2, 3, 4, 7, 5, 10, 3};
then peak is not 10, still 7

seydaozdemir
visit shbcf.ru