Peak element in an array in c

后端 未结 3 1822
情歌与酒
情歌与酒 2021-02-04 00:30

I am given an array of integers. I have to find a peak element in it. An array element is peak if it is NOT smaller than its neighbors. For corner elements,cons

3条回答
  •  臣服心动
    2021-02-04 01:11

    Yes, you can do it in O(log n) using an idea similar to binary search. Point to the middle of the vector and check its neighbours. If it is greater than both of its neighbours, then return the element, it is a peak. If the right element is greater, then find the peak recursively in the right side of the array. If the left element is greater, then find the peak recursively in the left side of the array.

提交回复
热议问题