Find Peak Element - LeetCode

·

2 min read

Problem Link

C++ Code

class Solution {
public:
    int findPeakElement(vector<int>& nums) {

        int n = nums.size();

        if(n == 1)
            return 0;

        int low = 0;
        int high = n-1;

        while(low <= high) {

            int mid = low + (high-low)/2;

            if(mid == 0) {

                if(nums[mid+1] < nums[mid]) {
                    return mid;
                } else {
                    low = ++mid;
                }

            } else if(mid == n-1) { 

                if(nums[mid-1] < nums[mid]) {
                    return mid;
                } else {
                    high = --mid;
                }

            } else if(nums[mid] > nums[mid+1] && nums[mid] > nums[mid-1]) {

                return mid;

            } else if(nums[mid-1] < nums[mid] && nums[mid] < nums[mid+1]) {

                low = ++mid;

            } else {

                high = --mid;

            }

        }

        return -1;
    }
};

TypeScript Code

function findPeakElement(nums: number[]): number {

    const n: number = nums.length;

    if(n == 1)
        return 0;

    let low: number = 0;
    let high: number = n-1;

    while(low <= high) {

        let mid: number = low + Math.floor((high-low)/2);

        if(mid == 0) {

            if(nums[mid+1] < nums[mid]) {
                return mid;
            } else {
                low = ++mid;
            }

        } else if(mid == n-1) { 

            if(nums[mid-1] < nums[mid]) {
                return mid;
            } else {
                high = --mid;
            }

        } else if(nums[mid] > nums[mid+1] && nums[mid] > nums[mid-1]) {

            return mid;

        } else if(nums[mid-1] < nums[mid] && nums[mid] < nums[mid+1]) {

            low = ++mid;

        } else {

            high = --mid;

        }

    }

    return -1;

};

Go Code

func findPeakElement(nums []int) int {

    n := len(nums);

    if n == 1 {
        return 0;
    }

    low := 0;
    high := n-1;

    for low <= high {

        mid := low + (high-low)/2;

        if mid == 0 {

            if nums[mid+1] < nums[mid] {
                return mid;
            } else {
                low = mid+1;
            }

        } else if mid == n-1 { 

            if nums[mid-1] < nums[mid] {
                return mid;
            } else {
                high = mid-1;
            }

        } else if nums[mid] > nums[mid+1] && nums[mid] > nums[mid-1] {

            return mid;

        } else if nums[mid-1] < nums[mid] && nums[mid] < nums[mid+1] {

            low = mid+1;

        } else {

            high = mid-1;

        }

    }

    return -1;
}