zoukankan      html  css  js  c++  java
  • leetcode 162. Find Peak Element


    Hi 大家,这道题是leetcode上的find peak element的题,不是lintcode的那道,

    这两道题是有区别的,lintcode的题目中说明了:只有某个数左右两侧的元素都小于它,这个数才是峰值,

    而leetcode的题,是只要找到个最大值就行,可以是[1,2]里的2这种。

     

    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.

    这道题用二分法

    public class Solution {
        public int findPeakElement(int[] nums) {
            if (nums.length <= 1){
                return 0;
            }
            int start = 0, end = nums.length - 1; 
            while(start + 1 <  end) {
                int mid = start + (end - start) / 2;
                if(nums[mid] < nums[mid - 1]) {
                    end = mid;
                } else {
                    start = mid;
                }
            }
            if(nums[start] < nums[end]) {
                return end;
            } else { 
                return start;
            }
        }
    }
  • 相关阅读:
    2021/6/17学期总结
    2021/6/16申请加分
    2021/6/15
    2021/6/14
    2021/6/11
    2021/6/10
    2021/6/9
    2021/6/8
    2021/6/7
    2021/6/5读书笔记
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5760513.html
Copyright © 2011-2022 走看看