162. Find Peak Element
来源:互联网 发布:cv 知乎 编辑:程序博客网 时间:2024/05/17 00:58
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.
題意:
找到一串數字的山頂元素(最大元素),例如:[1,2,3,1],山頂元素為3
題解:
會有三種情況:
- 有山頂:[1,5,2,3,1]=>5
- 右偏斜:[4,2,3,1]=>4
- 左偏斜:[1,3,2,5,7]=>7
依照以上三種情況來編寫代碼
package LeetCode.Medium;/* * 山峰型,返回山頂數字的index * ex:12321 * return 2 * ex:12323421 * return 5 * * 右偏斜型,返回第0個 * ex:321 * return 0 * 左偏斜型,返回最後一個 * ex:123 * return 2 */public class FindPeakElement { public int findPeakElement(int[] nums) { boolean isSkew = true; int peak_index = 0; //開始尋找山頂 for(int i = 1; i < nums.length; i ++) { if(i + 1 >= nums.length) { break; } //若找到山頂則不是偏斜 if(nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) { peak_index = i; isSkew = false; break; } } //̎處理偏斜的部分 if(isSkew == true && nums.length > 1) { if(nums[0] > nums[1]) { peak_index = 0; } else if(nums[1] > nums[0]){ peak_index = nums.length - 1; } } return peak_index; }}
阅读全文
0 0
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- 162. Find Peak Element
- RK3328-evb固件烧录
- C++&Pascal&Java——NOIP2015提高组day1 t1——神奇的幻方
- Minesweeper(深搜)
- IO流之File详细用法
- C语言结构体(struct)常见使用方法
- 162. Find Peak Element
- iOS Invalid bitcode signature(Linker command falied with exit code 1 (use -v to see invocation))
- QT中的GL
- 飞腾1500A平台上构建Go语言环境指南
- QT中的GL
- HDU 6105 Gameia
- JAVA 判断一个字符串是不是一个合法的日期格式
- 图片边缘出现黑点的问题分析和解决(纹理过滤)
- 【主席树 求区间第k大】poj 2104 K-th Number