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=







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章