A peak element is an element, which is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1] , the find a peak element and return its index.
The array may be contain multiple peaks, in this case return the index to any one of the peaks is fine.
May imagine 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.
Note:
Your solution should is in logarithmic complexity.
Problem Solving Ideas:
In the tip of the topic, the time complexity of log (n) is required, so only the idea of divide and conquer, similar to merge sort, is implemented in Java as follows:
public int findpeakelement (int[] nums) {if (nums.length==1| | NUMS[0]>NUMS[1]) return 0; if (Nums[nums.length-1]>nums[nums.length-2]) return nums.length-1; int left=1,right=nums.length-2,mid= (left+right)/2; if (Findpeakelement (nums,mid,right) ==-1) return findpeakelement (Nums,left,mid); Return findpeakelement (nums,mid,right); } static public int findpeakelement (int[] Nums,int left,int right) {if (left==right) {if (nums[left]>nums[left- 1]&&NUMS[LEFT]>NUMS[LEFT+1]) return left; return-1; } else if (left==right-1) {if (nums[left]>nums[left-1]&&nums[left]>nums[left+1]) return left; else if (nums[right]>nums[right-1]&&nums[right]>nums[right+1]) return right; return-1; } int mid= (left+right)/2; if (Findpeakelement (nums,mid+1,right) ==-1) return findpeakelement (Nums,left,mid); Return findpeakelement (nums,mid+1,right); }
Java for Leetcode 162 Find Peak Element