LeetCode -- Find Peak Element
2015-10-11 22:31
225 查看
题目描述:
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
= -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
在一个序列中,找到nums[i] > nums[i-1] && nums[i] > nums[i+1]的索引i。
本题可以理解为在1个不连续的点集中,找到极大值点(先增后减)。
本题是一个典型的二分法查询问题:
1.如果序列本身是递减,nums[0]就是极大值点。
2.如果序列末尾处递增,nums[len -1]就是极大值点。
3.如果nums[i] > nums[i+1] 且 nums[i] > nums[i-1],那么nums[i]就是极大值。
4.如果序列在nums[i]处递增,即nums[i-1] < nums[i] < nums[i+1],那么右边一定存在极大值。
5.如果序列在nums[i]处递减,即nums[i-1] > nums[i] > nums[i+1],左边一定存在极大值。
实现代码:
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
= -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
在一个序列中,找到nums[i] > nums[i-1] && nums[i] > nums[i+1]的索引i。
本题可以理解为在1个不连续的点集中,找到极大值点(先增后减)。
本题是一个典型的二分法查询问题:
1.如果序列本身是递减,nums[0]就是极大值点。
2.如果序列末尾处递增,nums[len -1]就是极大值点。
3.如果nums[i] > nums[i+1] 且 nums[i] > nums[i-1],那么nums[i]就是极大值。
4.如果序列在nums[i]处递增,即nums[i-1] < nums[i] < nums[i+1],那么右边一定存在极大值。
5.如果序列在nums[i]处递减,即nums[i-1] > nums[i] > nums[i+1],左边一定存在极大值。
实现代码:
public class Solution { public int FindPeakElement(int[] nums) { if(nums.Length == 0){ return -1; } if(nums.Length == 1){ return 0; } if(nums.Length == 2){ return nums[0] > nums[1] ? 0 : 1; } if(nums[nums.Length - 1] > nums[nums.Length - 2]){ return nums.Length -1; } if(nums[0] > nums[1]){ return 0; } var l = 0; var r = nums.Length - 1; while(l < r - 1){ var m = (l + r) / 2; if(nums[m] > nums[m-1] && nums[m] > nums[m+1]){ return m; } else if(nums[m] > nums[m-1] && nums[m] < nums[m+1]){ // increasing , go right l = m; } else { // decreasing , go left r = m; } } return -1; } }
相关文章推荐
- 查看Mat对象的数据的三种方法
- Python 流程控制
- 功能测试定义
- IOS开发-本地通知
- 这类问题需要利用二进制的特殊性
- 利用windows系统ftp命令编写的BAT文件上传[转]
- 一路大创 一路惨淡
- IE 下 img click 事件 src 不起作用
- FZU - 2150 Fire Game(15.10.10 搜索专题)bfs
- lock
- 【转帖】C#与C Windows API数据类型对应关系
- 50个人围成一圈
- java中nextLine()和next()的区别
- Bat脚本处理ftp超强案例解说
- 大整数 除法
- 透过HT for Web 3D看动画Easing函数本质
- Product of Array Except Self
- 项目35.4 贪财的富翁
- 慕课网android 学习笔记
- 2015-10-10