Leetcode the problem of find Peak element
Elements larger than the left and right two elements we call vertex elements, in a given array, no contiguous two elements are equal. Find the subscript of one of the vertex elements in this array, and if there are multiple, give any one of them. You can default an infinitesimal element at both ends of a given array, that is, the vertex element of the array [1] is labeled 0.
Note the point:
- Control the complexity of time to log (n)
Example:
Input: Nums = [1, 2, 3, 1]
Output: 2
Thinking of solving problems
/ / \/\ / / \/ / \
As you can see, there is at least one vertex element sandwiched between a rising edge and a falling edge. Since there is an infinitesimal element on both sides of the left and right side, the leftmost edge of the beginning is ascending, and the rightmost edge is descending. Requiring a time complexity of log (n), we can judge by binary search. We take the midpoint and a point behind it, if the edges of these two points are ascending, then we discard the points to the left of the midpoint, while the left side is still up, the rightmost side is down, and if the edges of the two points are falling, then the point to the right of the midpoint is dropped, so that it still satisfies the above requirements. To ensure that there is at least one vertex element between the left and right two points. As for how to choose the New left and right nodes in two points, we should try to make the new right and left nodes close to the vertex elements as far as possible, because the final termination condition is coincident. So when you select the New left node, the next node of the point should be selected, and when the New Right node is selected, the midpoint is selected.
AC Source
class solution(object): def findpeakelement(self, nums): "" : Type Nums:list[int]: Rtype:int " " "Left, right =0, Len (nums)-1 whileLeft < Right:mid = (right + left)//2 ifNums[mid] < Nums[mid +1]: Left = mid +1 Else: Right = MidreturnLeftif__name__ = ="__main__":assertSolution (). Findpeakelement ([1,2,3,1]) ==2
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Find Peak Element