代码面试题:find a peak (二分法)

Given an array of integers. Find a peak element in it. An array element is peak if it is NOT smaller than its neighbors. For corner elements, we need to consider only one neighbor. For example, for input array {5, 10, 20, 15}, 20 is the only peak element. For input array {10, 20, 15, 2, 23, 90, 67}, there are two peak elements: 20 and 90. Note that we need to return any one peak element.

Following corner cases give better idea about the problem.
1) If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}.
2) If input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}.
3) If all elements of input array are same, every element is a peak element.


O(n)的方法就是线性扫描。用二分法,注意考虑corner elements。

int findPeak(int num[], int length) {
	int start = 0;
	int end = length - 1;
	while (start + 1 < end) {
		int mid = start + (end - start) / 2;
		if (num[mid] >= num[mid + 1] &&  num[mid] >= num[mid - 1]) {
			return num[mid];
		}
		else if (num[mid] < num[mid - 1]) {
			end = mid;
		}
		else {
			start = mid;
		}
	}
	if ((start == 0 || num[start] >= num[start - 1]) && num[start] >= num[start + 1]) {
		return num[start];
	}
	else if ((end == length - 1 || num[end] >= num[end + 1]) && num[end] >= num[end - 1]) {
		return num[end];
	}
	else {
		return -1;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值