Find Peak Element, findpeakelement

Source: Internet
Author: User

Find Peak Element, findpeakelement

Original question link: https://oj.leetcode.com/problems/find-peak-element/

Given an array with unequal adjacent elements, find a local maximum and return the corresponding subscript.

Method 1: sequential traversal.

An important feature of this question is that, starting from the first element, if it is greater than the adjacent subsequent element, the first element is a local maximum value and can be returned. If it is smaller than the adjacent subsequent element, the second element is greater than the first element. In this way, the array is traversed one by one. If the first element is larger than its adjacent subsequent element, the element is a local maximum value and can be returned. The Code is as follows:

class Solution {public:    int findPeakElement(const vector<int> &num) {        for(int i=1;i<num.size();i++){            if(num[i]<num[i-1])                return i-1;        }        return num.size()-1;    }};

Time Complexity: Worst O (N)

Method 2: Binary Search

Idea: If the intermediate element is greater than its adjacent subsequent element, the left side of the intermediate element (including the intermediate element) must contain a local maximum value. If the intermediate element is smaller than its adjacent subsequent element, the right side of the intermediate element must contain a local maximum value.

class Solution {public:    int findPeakElement(const vector<int> &num) {        int left=0,right=num.size()-1;        while(left<=right){            if(left==right)                return left;            int mid=(left+right)/2;            if(num[mid]<num[mid+1])                left=mid+1;            else                right=mid;        }    }};
Time Complexity: O (lgN)

The question is good. It is a continuation of binary search and can be summarized together with the binary search algorithm.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.