Header Ad

Leetcode Find Peak Element problem solution

In this Leetcode Find Peak Element problem solution, A peak element is an element that is strictly greater than its neighbors. Given an 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] = -∞. You must write an algorithm that runs in O(log n) time.

Leetcode Find Peak Element problem solution


Problem solution in Python.

class Solution:
    def findPeakElement(self, nums):
        if len(nums) == 1:
            return 0
        left, right = 0, len(nums) - 1
        while left < right:
            mid = (left + right) // 2
            if nums[mid] > nums[mid+1]:
                right = mid
            else:
                left = mid + 1
        return left



Problem solution in Java.

public class Solution {
    public int findPeakElement(int[] nums) {
        int peakIndex;
        if(nums.length == 1) return 0;
        if(nums[nums.length-1] > nums[nums.length-2] ) return nums.length-1;
        int j = 1, k = nums.length-2;
        while(j<k){
            int check = (j + k)/2;
            if(nums[check] > nums[check + 1] && nums[check] > nums[check-1])
                return check;

            else if(nums[check] < nums[check+1]){
                j = check+1;
            }
            else{
                k = check-1;
            }
        }
        return k;
    }
}


Problem solution in C++.

public:
    int findPeakElement(vector<int>& nums) {
        int len = nums.size();
        if(len == 1)return 0;
        if(nums[0] > nums[1])return 0;
        if(nums[len-1] > nums[len-2]) return len-1;
        
        for(int i=1; i<len-1; i++){
            if(nums[i-1] < nums[i] && nums[i] > nums[i+1])return i;
        }
        return -1;
    }
};


Problem solution in C.

int findPeakElement(int* nums, int numsSize){
    if(numsSize==1)
    {
        return 0;
    }
    if(nums[0]>nums[1])
    {
        return 0;
    }
    if(nums[numsSize-1]>nums[numsSize-2])
    {
        return numsSize-1;
    }
    for(int i=1;i<numsSize-1;i++)
    {
        if(nums[i-1]<nums[i]&&nums[i]>nums[i+1])
        {
            return i;
        }
    }
    return;
}


Post a Comment

0 Comments