zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    zabbix
    Tomcat 部署Web应用
    WebLogic
    WebLogic部署集群和代理服务器
    WebLogic 中的基本概念
    GIT详解和GITHUB
    Tomcat 内存溢出对应解决方式
    apache和tomcat区别
    数据库介绍
    The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4933312.html
Copyright © 2011-2022 走看看