Tuesday, January 20, 2015

[Leetcode] 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.
Analysis:
Pretty strait forward. Given num[-1] = num[n] = -∞ and num[i] ≠ num[i+1], if num[0] is greater than num[1], num[0] will be the peak since num[0] > num[1] and num[0] > num[-1]. If not, then num[1] could be the peak if num[1] > num[2], which could be computed in the next loop.  



    int findPeakElement(const vector &num) {
        if (num.size() == 1)
            return 0;
        int peak = 0;
        for(int i=1; i < num.size(); i++)
        {
            if (num[i] < num[peak])
                return i-1;
            else
                peak = i;
        }
        
        return peak;
    }

No comments:

Post a Comment