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;
            }
        }
    }
  • 相关阅读:
    今天面试一些程序员(新,老)手的体会
    UVA 10635 Prince and Princess
    poj 2240 Arbitrage
    poj 2253 Frogger
    poj 2485 Highways
    UVA 11258 String Partition
    UVA 11151 Longest Palindrome
    poj 1125 Stockbroker Grapevine
    poj 1789 Truck History
    poj 3259 Wormholes
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5760513.html
Copyright © 2011-2022 走看看