LeetCode Find Peak Element

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] = -∞.

Example 1:

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

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.

Note:

Your solution should be in logarithmic complexity.


要求在一个数组中找一个局部峰值的下标,局部峰值就是大于其左右相邻的两个元素。
暴力方法就是线性查找。更好一点的方法就是二分查找。如果中值nums[m]正好大于其左右相邻的元素,则返回m;如果nums[m]<nums[m-1],则在左边查找,因为nums[m-1]已经大于其右半边了,所以左边很有希望找到峰值,如果nums[m-1]>nums[m-2]也成立,则nums[m-1]就是峰值;否则继续往左边找,因为nums[-1]=-∞,所以肯定能找到一个局部峰值。右边也是类似。
代码如下:

class Solution {
public:
    int findPeakElement(vector<int>& nums)
    {
        int n = nums.size();
        if (n == 1)
            return 0;
        int l = 0, r = n – 1, m = 0;
        while (l <= r) {
            m = (l + r) / 2;
            if ((m == 0 || nums[m] > nums[m – 1]) && (m == n – 1 || nums[m] > nums[m + 1]))
                return m;
            if (m > 0 && nums[m] < nums[m – 1])
                r = m – 1;
            else
                l = m + 1;
        }
        return m;
    }
};

本代码提交AC,用时6MS。

二刷。相同思路,不同代码:

class Solution {
public:
	int findPeakElement(vector<int>& nums) {
		int n = nums.size();
		if (n == 1)return 0;
		if (n == 2)return nums[0] > nums[1] ? 0 : 1;

		int l = 0, r = n - 1;
		while (l <= r) {
			if (r - l <= 1)return nums[l] > nums[r] ? l : r;

			int mid = l + (r - l) / 2;
			if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1])return mid;
			if (nums[mid] < nums[mid - 1]) {
				r = mid - 1;
			}
			else {
				l = mid + 1;
			}
		}
		return 0;
	}
};

本代码提交AC,用时12MS。

Leave a Reply

Your email address will not be published. Required fields are marked *