leetcode題目例題解析(十四)

leetcode題目例題解析(十四)

Find Peak Element

題目描述:

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.

題意解析:

這道題就是找一個元素,他的左右鄰都比他小

解題思路:

直接按照問題,遍歷就可以了,注意兩端特殊情況

代碼:

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int length = nums.size();
        int flag;
        for(int i = 0; i < length; i++) {
            flag = 0;
            if (i == 0) {
                flag ++;
            } else if (nums[i - 1] < nums[i]){
                flag++;
            }
            if (i + 1 == length) {
                flag += 1;
            } else if (nums[i] > nums[i + 1]) {
                flag++;
            }
            if (flag == 2)
                return i;
        }
        return 0;
    }
};

原題目鏈接:
https://leetcode.com/problems/find-peak-element/description/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章