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);
        }
    };
  • 相关阅读:
    图书馆管理系统

    有理数类的设计
    题目4-多关键字排序(基于自定义比较函数)
    图总结
    树、二叉树、查找算法总结
    数据结构小结
    C语言文件
    第二次博客作业
    第一次博客作业
  • 原文地址:https://www.cnblogs.com/heyn1/p/10946596.html
Copyright © 2011-2022 走看看