LeetCode 162. Find Peak Element(查找峰值)
来源:互联网 发布:菊花插件dbm数据下载 编辑:程序博客网 时间:2024/06/03 07:29
原题网址:https://leetcode.com/problems/find-peak-element/
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.
click to show spoilers.
Note:
Your solution should be in logarithmic complexity.
方法一:全局扫描。
public class Solution { public int findPeakElement(int[] nums) { if (nums == null || nums.length==0) return -1; if (nums.length==1) return 0; if (nums[0] > nums[1]) return 0; if (nums[nums.length-2] < nums[nums.length-1]) return nums.length-1; for(int i=1; i<nums.length-1; i++) { if (nums[i-1] < nums[i] && nums[i] > nums[i+1]) return i; } return -1; }}
方法二:二分法。
public class Solution { public int findPeakElement(int[] nums) { int i=0, j=nums.length-1; while (i<j) { int m = (i+j)/2; if (nums[m] > nums[m+1]) j=m; else i=m+1; } return i; }}
0 0
- LeetCode 162. Find Peak Element(查找峰值)
- Leetcode 162 Find Peak Element 查找峰值元素(极大值)
- LintCode Find Peak Element(查找峰值)
- 【LeetCode】162.Find Peak Element 寻找峰值(二分法)
- LintCode Find Peak Element II(查找峰值II)
- [C++]LeetCode: 118 Find Peak Element (二分查找 寻找数组局部峰值)
- leetcode 162. Find Peak Element-查找峰元素|二分查找
- [LeetCode]162.Find Peak Element
- LeetCode 162. Find Peak Element
- [leetcode] 162.Find Peak Element
- 【LeetCode】162. Find Peak Element
- Leetcode 162. Find Peak Element
- [LeetCode]162. Find Peak Element
- 162. Find Peak Element LeetCode
- [LeetCode]162. Find Peak Element
- [LeetCode]162. Find Peak Element
- LeetCode *** 162. Find Peak Element
- leetcode.162. Find Peak Element
- 编译QT时出现lib/libQtGui.so: undefined reference to `ts_read_raw'的解决办法
- LeetCode 160. Intersection of Two Linked Lists
- LeetCode 161. One Edit Distance(编辑距离)
- Mac brew 安装mysql 以后启动报错
- JSON这样也可以,666
- LeetCode 162. Find Peak Element(查找峰值)
- 利用反射机制获得非静态内部类之getConstructor的用法探索
- Octave 线性代数 行列式 3
- shell 之 job
- 由数组随机化排序引出的对于js中sort()方法的理解分析
- 【线段树+dfs序 模板】hdu 5692 ,百毒之星A 题目 snacks dfs 序 +线段树维护最大值
- 设计模式 —— 抽象工厂模式(Abstract Factory)
- NYOJ-8-一种排序
- leetcode #29 in cpp