[LeetCode162]Find Peak Element

题目来源:https://leetcode.com/problems/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.

click to show spoilers.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

最容易想到的方法就是自左至右遍历数组,如果某元素比他左右元素都大,则返回该顶点。

class Solution162{
public:
	int findPeakElement(vector<int>& nums){
		//顺序查找
		int n = nums.size();
		if (n == 1)
			return 0;
		else if (nums[0] > nums[1])
			return 0;
		else if (nums[n - 1] > nums[n - 2])
			return n - 1;
		for (int i = 1; i < n - 1; ++i){
			if (nums[i - 1] <= nums[i] && nums[i + 1] <= nums[i])
				return i;
		}

		return -1;
	}
	
};


另一种方法是使用二分查找法解决问题。这个方法利用了题目中的如下性质:

1)最左边的元素,它“更左边”的元素比它小(负无穷),我们认为它是一个增长的方向

2)最右边的元素,它“更右边”的元素比它小(也是负无穷),我们认为它是一个下降的方向

根据这两点我们可以判断:最左边和最右边的元素围成的区域内,必有至少一个顶点

现在我们找到中点 nums[mid],将它与 nums[mid + 1] 作比较,如果前者较小,则方向是增长,与最左边的元素是一致的,就把左边界挪到mid+1的位置;

否则与最右边的元素一致,将右边界挪到mid的位置。

这个方法的原理就是当左边界方向为“增长”,右边界方向为“下降”时,二者围出的区域必有一个顶点。


class Solution162{
public:
	int findPeakElement(vector<int>& nums){
		//二分查找
		int n = nums.size();
		if (n == 1)
			return 0;

		int left = 0;
		int right = n - 1;
		int mid = 0;
		while (left < right){//注意该处是<
			mid = (left + right) / 2;
			if (nums[mid] <= nums[mid + 1])
				left = mid + 1;
			else{
				right = mid;
			}

		}
		
		return left;

	}
};
int main()
{
	Solution164 soulution;
	vector<int> v = { 1, 2, 3, 1 };
	cout << soulution.findPeakElement(v);

	system("pause");
	return 0;
}













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值