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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.


算法复杂度应在Logn内。所以猜想应该是用递归或者分治。注意题目有一个条件是很特殊的。就是Num[n]!=Num[n+1]

也就是说。要么大于 要么小于。第二个就是

You may imagine that num[-1] = num[n] = -∞.

说明可以从两头开始找。

先把能写的写了。

第一个就是判定规则,很简单

if(num[i]>num[i-1]&&num[i]>num[i+1]){
			return num[i];
		}
那么其实问题的关键在于查找方式。

我仍然想试一下遍历。但是因为有某种情况是可以做到skip的遍历。所以我认为这种情况是小于n的。但是能不能达到logn就不知道了。想试一下。

然後。就过了!!!你敢信!!就过了。。==。而且。。


public static int findPeakElement(int[] num) {
		for (int j = 0; j < num.length; j++) {
			if (num.length == 1) {
				return 0;
			} else if (j == 0) {
				if (num[0] > num[1]) {
					return 0;
				}
			} else if (j == num.length - 1) {
				if (num[num.length - 1] > num[num.length - 2]) {
					return num.length - 1;
				}
			} else if (num[j] > num[j - 1] && num[j] > num[j + 1]) {
				return j;
			}
		}
		return num.length - 1;
	}

这题到底难在哪啊。。。=0=







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值