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;
        }
    }
  • 相关阅读:
    第五周作业
    作业4
    20182302 2019-2020-1 《数据结构与面向对象程序设计》实验3报告
    作业四
    实验二
    实验一
    排序大集合java
    阿里面试——运筹优化工程师
    树的子结构判断
    剑指offer——合并两个排序的链表——对象、引用和赋值初接触
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4933312.html
Copyright © 2011-2022 走看看