p133 查找数组的波峰(leetcode 162)

2021-02-16 09:22

阅读:680

标签:++   class   vector   思路   min   time   value   find   tco   

一:解题思路

采用二分搜索的思想来做。

Time:O(log(n)),Space:O(1)

二:完整代码示例 (C++版和Java版)

C++:

class Solution {
public:
    int findPeakElement(vectorint>& nums) 
    {
        if (nums.size() == 0) return -1;
        int minValue = -2147483648;
        int low = 0, high = nums.size() - 1;
        while (low  high)
        {
            int mid = low + (high-low) / 2;
            int left = mid - 1 >= 0 ? nums[mid - 1] : minValue;
            int right = mid + 1 1] : minValue;
            if (nums[mid] > left && nums[mid] > right) return mid;
            else if (left > nums[mid]) high = mid - 1;
            else low = mid + 1;
        }

        return low;
    }
};

Java:

class Solution {
        public int findPeakElement(int[] nums)
        {
               if(nums==null || nums.length==0) return -1;
               int low=0,high=nums.length-1;
               while (lowhigh)
               {
                   int mid=low+(high-low)/2;
                   int left=mid-1>=0?nums[mid-1]:Integer.MIN_VALUE;
                   int right=mid+11]:Integer.MIN_VALUE;
                   if(nums[mid]>left && nums[mid]>right) return mid;
                   else if(left>nums[mid]) high=mid-1;
                   else low=mid+1;
               }

               return low;
        }
    }

 

p133 查找数组的波峰(leetcode 162)

标签:++   class   vector   思路   min   time   value   find   tco   

原文地址:https://www.cnblogs.com/repinkply/p/12708206.html


评论


亲,登录后才可以留言!