From f3cddc5118b8d410a6dc262f5c121ed60142468b Mon Sep 17 00:00:00 2001 From: Bugsource <35368347+Bugsource@users.noreply.github.com> Date: Tue, 30 Jul 2019 17:54:39 +0800 Subject: [PATCH] Create 162. Find Peak Element.md --- BinarySearch/162. Find Peak Element.md | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 BinarySearch/162. Find Peak Element.md diff --git a/BinarySearch/162. Find Peak Element.md b/BinarySearch/162. Find Peak Element.md new file mode 100644 index 0000000..4c53946 --- /dev/null +++ b/BinarySearch/162. Find Peak Element.md @@ -0,0 +1,60 @@ +# 题目描述 +``` +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. + +The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. + +You may imagine that nums[-1] = nums[n] = -∞. + +Example 1: + +Input: nums = [1,2,3,1] +Output: 2 +Explanation: 3 is a peak element and your function should return the index number 2. +Example 2: + +Input: nums = [1,2,1,3,5,6,4] +Output: 1 or 5 +Explanation: Your function can return either index number 1 where the peak element is 2, + or index number 5 where the peak element is 6. +``` + +# 解法 +此题就是考数学,如果一个区间[a,b], dfa/dx > 0, dfb/dx < 0, 则[a,b]上必有导数为0的点,即为极值点。 +## 解法1 +暴力扫描,不过注意到-1到0为递增,所以只要找到第一个递减的转折点,否则就是数组最末尾元素 +``` +class Solution { + public int findPeakElement(int[] nums) { + int preDirection = 1, len = nums.length; + for(int i = 1; i < len; i++){ + if(nums[i] < nums[i-1]){ + return i-1; + + } + } + return len-1;//如果能执行到这里,说明整个数组就是递增的 + } +} +``` + +## 解法2 +二分缩小查找范围,缩小依据即上文提到的数学原理 +``` +class Solution { + public int findPeakElement(int[] nums) { + int low = 0, high = nums.length-1; + while(low < high){ + int mid = low + (high-low)/2; + if(nums[mid] > nums[mid+1]){//high>=mid+1,所以mid+1不会越界 + high = mid;//查找区间缩小为[0,mid] + }else{ + low = mid+1;//[mid+1,high] + } + } + return low; + } +} +```