p133 查找数组的波峰(leetcode 162)
Posted repinkply
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } }
以上是关于p133 查找数组的波峰(leetcode 162)的主要内容,如果未能解决你的问题,请参考以下文章