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

一:解题思路

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

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

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

C++:

class Solution {
public:
    int findPeakElement(vector<int>& 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 < nums.size() ? nums[mid + 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 (low<high)
               {
                   int mid=low+(high-low)/2;
                   int left=mid-1>=0?nums[mid-1]:Integer.MIN_VALUE;
                   int right=mid+1<nums.length?nums[mid+1]: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;
        }
    }

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

时间: 04-15