zoukankan      html  css  js  c++  java
  • 162. 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>& a) {
            int i = 0;
            int j = a.size() - 1;
            if (j==0) return 0;
            while(i<j) {      
                if (a[i]<a[j]) {
                    i++;
                } else {
                    j--;
                }
            }
            return i;
        }
    };
    

      

     1 class Solution {
     2     public int findPeakElement(int[] nums) {
     3         int n  = nums.length;
     4         int lo = 0;
     5         int hi = n - 1;
     6         while(hi>lo){
     7             int mid = lo + (hi - lo)/2;
     8             if(nums[mid]<nums[mid+1])
     9                 lo = mid + 1;
    10             else
    11                 hi = mid;
    12         }
    13         return lo;
    14     }
    15 }
  • 相关阅读:
    Python
    Python
    Python
    Django REST framework
    Django REST framework
    Django REST framework
    Django REST framework
    jquery.unobtrusive-ajax.js的扩展,做到片段式加载
    jquery.unobtrusive-ajax.js单独的用法
    不复杂的Autofac注入
  • 原文地址:https://www.cnblogs.com/zle1992/p/8820156.html
Copyright © 2011-2022 走看看