zoukankan      html  css  js  c++  java
  • LeetCode-162 Find Peak Element

    题目描述

    A peak element is an element that is greater than its neighbors.

    Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

    The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

    You may imagine that nums[-1] = nums[n] = -∞.

    题目大意

    给定一个数组,寻找数组当中的任意一个顶点元素(顶点元素:该点的数值大于相邻位置的数值)的位置(数组中元素不重复)。

    要求:在O(log(n))时间复杂度内完成。

    示例

    E1

    Input: nums = [1,2,3,1]
    Output: 2

    E2

    Input: nums = [1,2,1,3,5,6,4]
    Output: 1 or 5 

    解题思路

    可以通过二分搜索策略进行搜索,判断条件为mid与mid + 1位置的数值大小进行搜索。

    复杂度分析

    时间复杂度:O(log(n))

    空间复杂度:O(1)

    代码

    class Solution {
    public:
        int findPeakElement(vector<int>& nums) {
            return solve(nums, 0, nums.size() - 1);
        }
        //二分搜索
        int solve(vector<int>& nums, int low, int high) {
            if(low == high) 
                return low;
            
            int mid1 = (low + high) / 2;
            int mid2 = mid1 + 1;
            //寻找两个较大的数字之间的数字的位置
            if(nums[mid1] > nums[mid2])
                return solve(nums, low, mid1);
            else
                return solve(nums, mid2, high);
        }
    };
  • 相关阅读:
    [FlareOn4]greek_to_me
    [FlareOn1]Sploitastic
    [FlareOn1]Creation
    [FlareOn1]5get_it
    esxi6.7中,显卡设置为直通步骤
    esxi6.7安装步骤
    nmcli命令详解
    查看指定进程的IO/CPU/MEM/带宽/显卡
    使用WSGIServer修改静态文件
    k8s配置多端口ingress
  • 原文地址:https://www.cnblogs.com/heyn1/p/10946596.html
Copyright © 2011-2022 走看看