【leetcode】162. Find Peak Element
来源:互联网 发布:阿里云栖大会地址 编辑:程序博客网 时间:2024/05/17 07:15
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.
解题思路:
当前值与周围相邻的比较,需要注意边界问题,如果只有一个元素,则其本身就是peak
如果是递增序列,则最后一个是peak
如果是递减序列,则第一个是peak
python:
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ n = 0 if len(nums) == 1 : return n for x in range(1, len(nums)-1): if nums[x]> nums[x-1] and nums[x]>nums[x+1]: return x if nums[len(nums)-1] > nums[0]: return len(nums)-1 else: return n
C++第一次尝试刷题:nums.size()可以直接取形参数组的长度。
class Solution {public: int findPeakElement(vector<int>& nums) { if (nums.size()==1){ return 0; } int i = 0; int len = nums.size(); for(i = 1;i<len-1; i++){ if (nums[i]>nums[i-1] && nums[i]>nums[i+1]) { return i; } } if (nums[len-1] > nums[0]){ return len-1; } else{ return 0; } return 0; }};
0 0
- [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
- 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
- mysql权限
- HTML5 为何要引入Canvas?
- codewars 一个很神奇的网站
- 微信公众号Unauthorized API function
- 全球购重构代码心得
- 【leetcode】162. Find Peak Element
- 你不可不知的final(1)-引入及特点
- 几种消息队列的比较
- 如何在经典的内转子无刷电机绕组示意图用右手定则判定线圈的感生电动势的方向
- 定位集群产生的接口问题
- Mysql存储emoji表情
- 关于lisener的错误
- PHP中const与define的区别
- 深入分析Linux自旋锁