[Leetcode] Find Peak Element

Posted seako

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Find Peak Element相关的知识,希望对你有一定的参考价值。

技术图片

找出一個大於兩邊的頂點,可以把nums[-1] ,nums[n] 都視為負無限

因為我用 int.minvalue來代表 num[-1] 及 num[n]的值

所以leetcode的test case 有一個測試是 [-2147483648] ,用來坑minvalue的

public class Solution
    {
        public int FindPeakElement(int[] nums)
        {
            int leftNeighber = int.MinValue;
            int rightNeighber = int.MinValue;
            int current = int.MinValue;
            int result = -1;
            for(int i = 0; i < nums.Length; i++)
            {
                current = nums[i];

                if(i -1 >=0 && i -1 <= nums.Length - 1)
                {
                    leftNeighber = nums[i - 1];
                }
                else
                {
                    leftNeighber = int.MinValue;
                }

                if (i + 1 >= 0 && i + 1 <= nums.Length - 1)
                {
                    leftNeighber = nums[i + 1];
                }
                else
                {
                    rightNeighber = int.MinValue;
                }

                if ((leftNeighber == int.MinValue || current > leftNeighber) && 
                    (rightNeighber == int.MinValue || current > rightNeighber))
                {
                    result = i;
                    break;
                }

                
            }
            return result;
        }
    }

 

技术图片

 

以上是关于[Leetcode] Find Peak Element的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 162 Find Peak Element(二分法)

leetcode162 Find Peak Element

刷题-LeetCode162 Find Peak Element

LeetCode 162. Find Peak Element 20170706

LeetCode Find Peak Element

leetcode 162. Find Peak Element --------- java