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.

题意:

给定一个数组,求这个数组中的某一个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;
		}
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值