• LeetCode OJ: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.

    感觉不太像medium的题目,但是我写的比价乱啊,代码如下:

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

    java代码:

    public class Solution {
        public int findPeakElement(int[] nums) {
            if(nums.length == 0 || nums.length == 1)
                return 0;
            if(nums[0] > nums[1])
                return 0;
            for(int i = 1; i < nums.length; ++i){
                if(nums[i] > nums[i - 1]){
                    if(i+1 >= nums.length || nums[i] > nums[i+1])
                        return i;
                }
            }
            return nums.length - 1;
        }
    }
  • 相关阅读:
    保险精算导论
    天津大学C语言程序设计
    会计学
    WIN10 CH340安装失败
    好用的浏览器插件
    好用的壁纸软件
    30讲 窗口看门狗
    STM32替换Arduino直通车
    stm32系列芯片独立看门狗(IWDG)溢出时间计算原理
    AD 电子元器件图片、名称及符号对照
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4933312.html
Copyright © 2020-2023  润新知