您的位置:首页 > 其它

Leetcode_162_Find Peak Element

2015-02-02 21:04 411 查看
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43415313

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

For example, in array
[1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.

思路:

(1)题意为给定一个整型数组,从中找出某一个元素,使得该元素比其左右元素都大,求该元素在数组中的位置。

(2)该题考查的对数组中元素大小的比较。该题还是挺简单的,只不过需要注意的是数组前两个元素和最后两个元素之间的比较。遍历数组一次,即可得到所得元素的下标。只不过这样的解题方法太低端,效率肯定不好。好的方法目前尚未想到,待后续想到再进行补充。这里就不啰嗦,详情见下方代码。

(3)希望本文对你有所帮助。

算法代码实现如下:

/**
* @author liqq
*/
public int findPeakElement(int[] num) {
int len = num.length;
if (num == null || len < 2) {
return 0;
}

if (len == 2 && num[0] < num[1]) {
return 1;
}

for (int i = 1; i < len; i++) {
if (i + 1 < len && num[i] > num[i - 1] && num[i] > num[i + 1]) {
return i;
}
}

if (num[0] > num[1]) {
return 0;
}

if (num[len - 1] > num[len - 2]) {
return len - 1;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: