[Sword pointing to offer|6. Looking for peaks]

0. Find peaks

image-20230411002039278

key point:

  • Just return the subscript of any peak value
  • nums[-1]=nums[n]=negative infinity

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is the peak element and your function should return its index 2

1. Programming for fools (just for fun)

class Solution {
public:
    int findPeakElement(vector<int>& a) {
        int n=a.size();
        if(n==1)
        {
            return 0;
        }
        if(n==2)
        {
            if(a[0]>a[1])
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
        for(int i=1;i<n-1;i++)
        {
            if(a[0]>a[1]) return 0;
            if(a[n-2]<a[n-1]) return n-1;
            if(a[i]>a[i-1]&&a[i]>a[i+1]) return i;
        }
        return -1;
    }
};

2. Two points

Seeing that the time complexity required by the question is o(logN), binary search is given priority, but the premise of binary search seems to be orderly. In fact, through this question we can also find that using the binary method does not necessarily require order, only order . You can be sure that the answer will appear on one of the sides

image-20230411001932419

int findPeakElement(int* nums, int numsSize){
    int left=0,right=numsSize-1;
    while(left<right)//
    {
        int mid=left+(right-left)/2;
        if(nums[mid+1]>=nums[mid])
        {
            left=mid+1;//
        }
        else if(nums[mid+1]<nums[mid])
        {
            right=mid;//
        }
    }
    return left;
}

key point:

  • Because of the characteristics of integer division mid=(left+right)/2, rounding down, as long as the number of array elements is greater than or equal to 2, the mid+1 subscript must exist (when the array element is equal to 1, left==right , will not enter the loop), and the mid-1 subscript does not necessarily exist, mid-1>=0 reduces boundary discussions
  • Note that the range of [left,right] is the area where the answer is located
  • Finally, when left==right, locate the peak position

image-20230411000822800

Guess you like

Origin blog.csdn.net/qq_64428099/article/details/130073265