LeetCode 题解(137): Find Peak Element
来源:互联网 发布:如何提高淘宝店铺的销量 编辑:程序博客网 时间:2024/06/10 04:12
题目:
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
Note:
Your solution should be in logarithmic complexity.
题解:
规定要Logn复杂度,所以只能Binary Search。思路是: 如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。
C++版:
class Solution {public: int findPeakElement(vector<int>& nums) { int l = 0, r = nums.size() - 1; while(l <= r) { if(l == r) return l; int mid = (l + r) / 2; if(nums[mid] > nums[mid + 1]) r = mid; else l = mid + 1; } }};
Java版:
public class Solution { public int findPeakElement(int[] nums) { int l = 0, r = nums.length - 1; while(l <= r) { if(l == r) return l; int mid = (l + r) / 2; if(nums[mid] > nums[mid + 1]) r = mid; else l = mid + 1; } return 0; }}
Python版:
class Solution: # @param nums, an integer[] # @return an integer def findPeakElement(self, nums): if len(nums) == 1: return 0 l, r = 0, len(nums) - 1 while l <= r: if l == r: return l mid = (l + r) / 2 if nums[mid] > nums[mid+1]: r = mid else: l = mid + 1
0 0
- LeetCode 题解(137): Find Peak Element
- leetcode题解-162. Find Peak Element
- [LeetCode] Find Peak Element
- Leetcode:Find Peak Element
- LeetCode Find Peak Element
- leetcode: Find Peak Element
- leetcode:Find Peak Element
- LeetCode Find Peak Element
- Find Peak Element --leetcode
- Leetcode Find Peak Element
- [LeetCode] Find Peak Element
- Leetcode Find Peak Element
- Leetcode: Find Peak Element
- 【leetcode】Find Peak Element
- leetcode:Find Peak Element
- 【Leetcode】Find Peak Element
- LeetCode:Find Peak Element
- LeetCode:Find Peak Element
- SimpleAdapter
- libmysl 开发遇到的问题
- 【leetcode c++】67 Add Binary
- Android Support库百分比布局
- 可拖拽listview基本使用技巧(DragSortListView)
- LeetCode 题解(137): Find Peak Element
- 黑马程序员-OC语言-封装的概念及原理(听课笔记)
- 循环赛日程表问题
- 避免碌碌无为的感觉
- AndroidAnnotations在Android Studio中的配置
- 在linux 下安装sublime text 2
- javascrip cookie
- 黑马程序员-OC语言-封装的实现步骤(听课笔记)
- php数组遍历