Find Peak Element--leetcode

Source: Internet
Author: User

Original title Link: https://oj.leetcode.com/problems/find-peak-element/

Topic: Given an array of unequal adjacent elements, find one of the local maximum value , return the corresponding subscript.

Method 1: Sequential traversal.

An important feature of the subject is that, starting with the first element, if it is larger than the next successive element, the first element is a local maximum value, which is returned. If it is less than the next successive element, the second element is greater than the first element. So, one by one times the first occurrence of the group, if the element i is greater than its adjacent subsequent elements, then the element is a local maximum value, return. 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: Two-point lookup

Idea: If the intermediate element is larger than its adjacent successive elements, the left side of the intermediate element (containing the intermediate element) must contain a local maximum value. If the intermediate element is smaller than its adjacent successive elements, 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 to left            ; int mid= (left+right)/2;            if (num[mid]<num[mid+1])                left=mid+1;            else                Right=mid;}}    ;
Complexity of Time: O (LgN)

The title is good, is binary search continuation, can and binary search related algorithms together to do a summary.

Find Peak Element--leetcode

Related Article

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.