首页 > 其他 > 详细

[Leetcode] Find Peak Element

时间:2019-05-19 23:25:23      阅读:155      评论:0      收藏:0      [点我收藏+]

技术分享图片

找出一個大於兩邊的頂點,可以把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

原文:https://www.cnblogs.com/seako/p/10891377.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!