題目:
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
Your solution should be in logarithmic complexity.
解答:
難度在於時間復雜度,需要是對數時間。又是搜索題,很自然會想到二分搜索。
我們來看中間位置發生的情況:
如果是1……2,3,2……9,那麼很自然可以返回3所在的位置作為一個峰值點;如果是1……2,3,4……9,那麼可以肯定峰值點出現在後半部分:3,4……9中;
class Solution { public: int findPeakElement(vector& nums) { int range = nums.size() - 1; if((range/2 - 1 >= 0) && (range/2 + 1 <= range)) { if((nums[range/2] > nums[range/2 - 1]) && (nums[range/2] > nums[range/2 + 1])) { return (range/2); } else if(nums[range/2] < nums[range/2 - 1]) { vector tmp(nums.begin(), nums.begin() + range/2); return findPeakElement(tmp); } else if(nums[range/2] < nums[range/2 + 1]) { vector tmp(nums.begin() + range/2, nums.end()); return (range/2 + findPeakElement(tmp)); // 注意基礎位置的偏移量 } } else { if(range == 0) return 0; if(range == 1) { if(nums[0] > nums[1]) return 0; else return 1; } } } };