题目:
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.
Your solution should be in logarithmic complexity.
题意:
给定一个数组,求这个数组中的某一个peek值,peek值这样定义的,要求它比它周围的数字都要大。但是要通过这道题却对思维的全面性的要求非常高,比如碰到数组中只有一个数字的时候,那么直接输出0;碰到数组中只有两个数字的时候,如果第一个数字大于第二个数字,那么直接返回的是0,否则返回的是1;还有就是碰到如果前面的数字都不满足,那么就是只有最后一个数字满足的时候,只要求是满足最后的这个数字比它之前的那个数字大就行。所以针对的是几个临界的情况,比如,数组的大小只有一个,或者是两个或者是头或者是尾巴的那两个节点的时候,只需要考虑的是比它周围的一个元素大就行,而在中间的那些元素就要求比它周围的两个元素大。所以这里考查的是思维的全面性。
public class Solution
{
public int findPeakElement(int[] nums)
{
int length = nums.length;
if(length == 0 || nums == null || length == 1)
return 0;
else if(length == 2)
{
if(nums[0] > nums[1])
return 0;
else
return 1;
} //思维的全面性
else
{
int i = 0;
for(i = 0; i < length - 1; i++)
{
if(i == 0)
{
if(nums[i] > nums[i + 1])
break;
}
else if(i != length - 1)
{
if(nums[i] > nums[i - 1] && nums[i] > nums[i + 1])
break;
}
else if(i == length - 1)
{
if(nums[i] > nums[i - 1])
break;
}
}
return i;
}
}
}