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);
        }
    };
  • 相关阅读:
    建模算法(九)——拟合 (转)
    Swift初探一
    D3DXMatrixMultiply 函数
    魔术师发牌和拉丁方阵
    strip 命令的使用方法
    GDI编程小结
    Android多媒体-MediaRecorder 录制音视频
    Android 使用Gson解析json案例具体解释
    有依赖的背包问题(背包九讲)
    c++ 正則表達式
  • 原文地址:https://www.cnblogs.com/heyn1/p/10946596.html
Copyright © 2011-2022 走看看