leetcode Question: Find Peak Element

Find Peak Element

A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Note:
Your solution should be in logarithmic complexity.

Analysis:

It is required to have log(N) complexity, for the single array, binary search is usually considered since it satisfied the log(N) requirement.
Be careful with the boundary conditions, it is a pretty simple problem.


Code(C++):

class Solution {
public:
    void fp(int st, int ed, const vector<int> &num, int &idx){
        if (st > ed || idx != -1){
            return;
        } else {
            int mid = st + (ed - st)/2;
            
            if (mid == num.size()-1 && num[mid]>num[mid-1]){
                idx = mid;
                return;
            }
            if (mid == 0 && num[mid]>num[mid+1]){
                idx = mid;
                return;
            }
            if (num[mid]>num[mid-1] && num[mid]>num[mid+1]){
                idx = mid;
                return;
            } 
            fp(st,mid-1,num, idx);
            fp(mid+1,ed,num, idx);
        }
    }

    int findPeakElement(const vector<int> &num) {
        if (num.size() == 1){
            return 0;
        }
        int idx = -1;
        fp(0, num.size()-1,num,idx);
        return idx;
    }
};

Code(Python):

class Solution:
    # @param num, a list of integer
    # @return an integer
    
    idx = -1
    def findPeakElement(self, num):
        if len(num) == 1:
            return 0
        self.fp(0, len(num)-1, num)
        return self.idx
        
    def fp(self, st, ed, num):
        if st > ed or self.idx != -1:
            return
        else:
            mid = st + (ed - st)/2;
            if mid == len(num)-1 and num[mid]>num[mid-1]:
                self.idx = mid
                return
            if mid == 0 and num[mid]>num[mid+1]:
                self.idx = mid
                return
            if num[mid]>num[mid-1] and num[mid]>num[mid+1]:
                self.idx = mid
                return
            self.fp(st,mid-1,num)
            self.fp(mid+1,ed,num)
        

1 comment:

  1. Hi Yu, you are looking at both segments beside mid, and there is no guarantee that the first segment it goes down along will have the answer. So it might come back and then go down the second segment as well. So isn't the worst case time complexity O(n) then ?

    ReplyDelete