C++ 寻找峰值

    //O(n),遍历
    int findPeakElement1(vector<int>& nums) 
    {
        const size_t length = nums.size() - 1;
        if (length == 0) return 0;
        if (nums[0] > nums[1])
            return 0;
        if (nums[length] > nums[length - 1])
            return length;
        for (size_t i = 1; i < length; i++)
        {
            if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1])
            {
                return i;
            }
        }
        return 0;
    }
    //O(n),哨兵遍历
    int findPeakElement2(vector<int>& nums)
    {
        nums.push_back(0x80000000);
        for (size_t i = 0; i < nums.size(); i++)
        {
            if (nums[i] > nums[i + 1])
            {
                return i;
            }
        }
        return 0;
    }
    //O(logn),二分
    int findPeakElement(vector<int>& nums)
    {
        int len = nums.size() - 1;
        int left = 0;
        int right = len;
        int mid;
        while (left < right)
        {
            mid = left + ((right - left) >> 1);//>>1是除2的意思
            if (nums[left] > nums[right])//判断向左,向右那边比较高
            {
                //判断当前位于正在上坡还是下坡
                if (nums[mid] > nums[left] && !(mid > 0 && nums[mid] < nums[mid - 1]))
                {
                    left = mid;
                }
                else
                {
                    right = mid - 1;
                }
            }
            else
            {
                //判断当前位于正在上坡还是下坡
                if (nums[mid] > nums[right] && !(mid < len && nums[mid] < nums[mid + 1]))
                {
                    right = mid;
                }
                else
                {
                    left = mid + 1;
                }
            }
        }
        return nums[left] > nums[right] ? left : right;
    }

 

posted @ 2021-10-24 10:56  mshentai  阅读(441)  评论(0编辑  收藏  举报