【leetcode刷题笔记】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.
Note:
Your solution should be in logarithmic complexity.
题解:题目要求用O(logn)的时间复杂度找到局部最大值,很容易想到二分算法。设置一个函数 private boolean findPeakHelper(int[] num,int begin,int end){ ,每次判断(begin+end)/2位置上的元素是否满足要求,如果不满足就搜索左半边数组,如果在左半边搜索到了,右半边就没有必要搜索了,因为题目只让返回一个解;如果左半边没搜索到,就继续递归搜索右半边。特别注意对位置0和位置n-1处元素的处理。
JAVA版本代码如下:
1 public class Solution { 2 int index = 0; 3 public int findPeakElement(int[] num) { 4 findPeakHelper(num, 0, num.length-1); 5 return index; 6 } 7 private boolean findPeakHelper(int[] num,int begin,int end){ 8 if(begin > end) 9 return false; 10 int mid = (begin + end)/2; 11 if(mid == 0) 12 { 13 if(mid+1 < num.length && num[mid+1] < num[mid]){ 14 index = mid; 15 return true; 16 }else { 17 return findPeakHelper(num, mid+1, end); 18 } 19 } 20 21 if(mid-1 >= 0 && mid == num.length-1){ 22 if(num[mid-1] < num[mid]){ 23 index = mid; 24 return true; 25 }else{ 26 return findPeakHelper(num, begin, mid-1); 27 } 28 } 29 30 if(num[mid-1] < num[mid] && num[mid+1] < num[mid]){ 31 index = mid; 32 return true; 33 } 34 35 if(findPeakHelper(num, begin, mid-1)) 36 return true; 37 else { 38 return findPeakHelper(num, mid+1, end); 39 } 40 } 41 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2014-04-02 【leetcode刷题笔记】Binary Tree Preorder Traversal
2014-04-02 【leetcode刷题笔记】Linked List Cycle