【LeetCode & 劍指offer刷題】查詢與排序題9:Find Peak Element
阿新 • • 發佈:2019-01-05
【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)
Find Peak Element
A peak element is an element that is greater than its neighbors. Given an input array nums , where nums[i] ≠ nums[i+1] , find a peak element and return its index.C++ //問題:找極大值元素(返回任意一個極大值均可) /* 方法一:找最大值一定是極大值 O(n) */ class Solution { public : int findPeakElement ( vector < int >& nums ) { int n = nums . size (); if ( n == 0 ) return - 1 ; //為空時,返回-1 int max_index = 0 ; for ( int i = 0 ; i < n ; i ++) //找序列中的最大值,一定是極大值 { if ( nums [ i ]> nums [ max_index ]) max_index = i ; } return max_index ; } }; /* 掌握 方法二:藉助二分查詢思路 right指的數比後一個數大,left指的數比前一個數大,當兩個“指標”相遇時,就可以滿足極大值條件(兩個指標按二分跨度走,故效率較高) 有點像lower_bound函式 O(logn) */ class Solution { public : int findPeakElement ( vector < int >& nums ) { if ( nums . empty () return - 1 ; // 為空時,返回 -1 int left = 0 , right = nums . size ()- 1 ; while ( left < right ) //left = right 時退出迴圈,結果是 left,right,mid 均指向極大值位置 { int mid = ( left + right )/ 2 ; if ( nums [ mid ] < nums [ mid + 1 ]) //如果中間值比右邊值小,說明峰值在右邊 left = mid + 1 ; else // 如果中間值比右邊值大,說明峰值在左邊(包括 a[mid] ,故取 right=mid ) right = mid ; } return right; } };