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;
            }
        }
    }
  • 相关阅读:
    在eclipse中进行HotSpot的源码调试
    CentOS6.5上编译OpenJDK7源码
    商城楼层跳转
    javascript原生百叶窗
    javascript原生轮播
    Canvas计时器
    纯js模拟 radio和checkbox控件
    纯js日历
    关于匿名函数,闭包和作用域链
    端口占用问题
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5760513.html
Copyright © 2011-2022 走看看