题目描述:

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.

解题思路:

循环找一个最大数,进行替换。

代码:

 1 class Solution {
 2 public:
 3     int findPeakElement(vector<int>& nums) {
 4         int n = nums.size();
 5         if(n < 2)
 6             return 0;
 7         int max = nums[0], index = 0;
 8         for(int i = 1; i < n; i++){
 9             if(nums[i]>nums[i-1]){
10                 index = i;
11                 max = nums[i];
12             }
13         }
14         return index;
15     }
16 };

 

posted on 2018-04-01 18:29  宵夜在哪  阅读(80)  评论(0编辑  收藏  举报