【LeetCode】(162)Find Peak Element(Medium)
来源:互联网 发布:大数据分析工作 编辑:程序博客网 时间:2024/05/23 20:17
题目
Find Peak Element
Total Accepted: 36800 Total Submissions: 115427My SubmissionsA 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.
解析
就是顺序去比较就好了,不过需要考虑一些特殊情况,只有一个元素,只有两个元素,极值在最左边或者最右边。
class Solution {public: int findPeakElement(vector<int>& nums) { if (nums.size() == 1)return 0;if (nums.size() == 2)return nums[0]>nums[1]?0:1; for (int i = 1;i<nums.size();i++) {if (nums[i]>nums[i-1] && nums[i] > nums[i+1]) { return i; } }return nums[0]>nums.back()?0:nums.size()-1; }};网上有一个差不多,不过思路要清晰一些的,代码来自http://www.cnblogs.com/ganganloveu/p/4147655.html
int findPeakElement(vector<int>& nums) { int n = nums.size(); if(n == 1) return 0; if(nums[0] > nums[1]) return 0; if(nums[n-1] > nums[n-2]) return n-1; for(int i = 1; i < n-1; i ++) if(nums[i] > nums[i-1] && nums[i] > nums[i+1]) return i; }
0 0
- [Leetcode 162, Medium] Find Peak Element
- 【LeetCode】(162)Find Peak Element(Medium)
- Leetcode 162. Find Peak Element (Medium) (cpp)
- Find Peak Element [Medium]
- Medium 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
- Find Peak Element - LeetCode 162
- 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
- HDOJ 1407 测试你是否和LTC水平一样高
- [LeedCode OJ]#237 Delete Node in a Linked List
- PPT制作滚动文本的方法
- java使用poi解析或处理excel的时候,如何防止数字变成科学计数法的形式
- _stdcall,_cdecl区别
- 【LeetCode】(162)Find Peak Element(Medium)
- 华为OJ平台试题 ——数组:整形数组合并
- POJ 3532 双连通缩点
- tomcat部署多个项目webAppRootKey冲突
- PayPal开发之IPN的使用
- Android 打包签名(二)
- 打印结点和等于某个值的所有路径
- 使用strace, ltrace寻找故障原因的线索
- linux读取windows共享文件