Last updated on October 25th, 2024 at 10:20 pm
Here, We see Find Peak Element LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Array, Binary Search
Companies
Google, Microsoft
Level of Question
Medium
Find Peak Element LeetCode Solution
Table of Contents
Problem Statement
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
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: 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.
1. Find Peak Element LeetCode Solution C++
class Solution { public: int findPeakElement(vector<int>& nums) { int n = nums.size(); for(int i=0; i<n-1; i++){ if(nums[i] > nums[i+1]){ return i; } } return n-1; } };
2. Find Peak Element LeetCode Solution Java
class Solution { public int findPeakElement(int[] nums) { if(nums.length == 1) return 0; int n = nums.length; if(nums[0] > nums[1]) return 0; if(nums[n-1] > nums[n-2]) return n-1; int start = 1; int end = n-2; while(start <= end) { int mid = start + (end - start)/2; if(nums[mid] > nums[mid-1] && nums[mid] > nums[mid+1]) return mid; else if(nums[mid] < nums[mid-1]) end = mid - 1; else if(nums[mid] < nums[mid+1]) start = mid + 1; } return -1; } }
3. Find Peak Element LeetCode Solution JavaScript
var findPeakElement = function(nums) { let left = 0, right = nums.length-1, mid; while(left < right) { mid = Math.floor((right+left)/2); if(nums[mid] > nums[mid+1]) right = mid; else left = mid+1; } return left; };
4. Find Peak Element LeetCode Solution Python
class Solution(object): def findPeakElement(self, nums): left = 0 right = len(nums)-1 while left < right-1: mid = (left+right)/2 if nums[mid] > nums[mid+1] and nums[mid] > nums[mid-1]: return mid if nums[mid] < nums[mid+1]: left = mid+1 else: right = mid-1 return left if nums[left] >= nums[right] else right