Find Peak Element

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] = -∞.

Example 1:

Input: nums ={1,2,3,1}
Output: 2

Approach

Java

public class FindPeakElement {
    public static void main(String[] args) {
        int[] nums = { 1231 };
        System.out.println(findPeakElement(nums));
    }

    // method to find the peak element in the array
    static int findPeakElement(int[] nums) {
        int n = nums.length;
        int low = 0, high = n - 1;
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] > nums[mid + 1])
                high = mid;
            else
                low = mid + 1;
        }
        return low;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


//function to find the peak element in the
//array
int findPeakElement(vector<int&nums)
{
    int n = nums.size();
    int low = 0high = n - 1;
    while (low < high)
    {
        int mid = low + (high - low) / 2;
        if (nums[mid] > nums[mid + 1])
            high = mid;
        else
            low = mid + 1;
    }
    return low;
}

int main()
{
    vector<intnums = {1231};
    cout << findPeakElement(nums);
    return 0;
}



No comments:

Post a Comment