LeetCode_CC150
  • Introduction
  • LeetCode
    • Single Number
    • Contains Duplicate
    • Happy Number
    • Valid Anagram
    • Contains Duplicate II
    • Count Primes
    • Isomorphic Strings
    • Word Pattern
    • Island Perimeter
    • Find the Difference
    • Palindrome Permutation
    • Two Sum III - Data structure design
    • Number of Boomerangs
    • Longest Palindrome
    • Logger Rate Limiter
    • Find All Anagrams in a String
    • Keyboard Row
    • Distribute Candies
    • Shortest Word Distance
    • Majority Element
    • Plus One
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Pascal's Triangle
    • Remove Element
    • Rotate Array
    • Pascal's Triangle II
    • Two Sum II - Input array is sorted
    • Third Maximum Number
    • Max Consecutive Ones
    • K-diff Pairs in an Array
    • Maximum Product of Three Numbers
    • Maximum Distance in Arrays
    • Shortest Unsorted Continuous Subarray
    • Roman to Integer
    • Count and Say
    • Valid Parentheses
    • Longest Common Prefix
    • Valid Palindrome
    • Length of Last Word
    • Repeated Substring Pattern
    • Number of Segments in a String
    • Valid Word Abbreviation
    • Longest Uncommon Subsequence I
    • Student Attendance Record I
    • Reverse Words in a String III
    • Arranging Coins
    • Guess Number Higher or Lower
    • Search Insert Position
    • Min Stack
    • Diameter of Binary Tree
    • Unique Binary Search Trees
    • Unique Binary Search Trees II
    • Binary Tree Zigzag Level Order Traversal
    • Nim Game
    • Add Digits
    • Fizz Buzz
    • Climbing Stairs
    • Array Partition I
    • Power of Three
    • Power of Four
    • Power of Two
    • Ugly Number
    • Find All Numbers Disappeared in an Array
    • Find All Duplicates in an Array
    • Minimum Moves to Equal Array Elements
    • Meeting Rooms
    • Subsets
    • Subsets II
    • Count Complete Tree Nodes
    • Minimum Size Subarray Sum
    • Maximum Size Subarray Sum Equals k
    • Sparse Matrix Multiplication
    • Meeting Rooms II
    • Letter Combinations of a Phone Number
    • Binary Tree Vertical Order Traversal
    • Find the Celebrity
    • Merge Intervals
    • One Edit Distance
    • Multiply Strings
  • Array&String
    • Subarray Sum
    • Maximum Subarray
    • Intersection of Two Arrays
    • Intersection of Two Arrays II
    • Partition List
    • Merge Sorted Array
    • Two Sum
    • 3Sum
    • Product of Array Except Self
    • Rotate Image
    • Spiral Matrix
  • Linked List
    • Merge Two Sorted Lists
    • Insert into a Cyclic Sorted List
    • Sort List
    • Linked List Cycle
    • Copy List with Random Pointer
    • Add Two Numbers
    • Delete Node in a Linked List
    • Reverse Linked List
    • Odd Even Linked List
    • Intersection of Two Linked Lists
    • Palindrome Linked List
    • Insertion Sort List
    • Remove Linked List Elements
    • Remove Duplicates from Sorted List
    • Swap Nodes in Pairs
    • Remove Nth Node From End of List
  • Binary Search
    • Missing Number
    • Valid Perfect Square
    • 744. Find Smallest Letter Greater Than Target
    • Sqrt(x)
    • First Bad Version
    • Pow(x, n)
    • Find the Duplicate Number
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Total Occurrence of Target
    • Search in a Big Sorted Array
    • Longest Increasing Subsequence
    • Find Peak Element
    • Search in Rotated Sorted Array
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Closest Number in Sorted Array
    • Search in Rotated Sorted Array II
    • Search for a Range
    • Maximum Number in Mountain Sequence
    • Last Position of Target
    • K Closest Numbers In Sorted Array
    • Sqrt(x) II
  • Binary Tree
    • Maximum Depth of Binary Tree
    • Invert Binary Tree
    • Same Tree
    • Binary Tree Paths
    • Lowest Common Ancestor of a Binary Search Tree
    • Balanced Binary Tree
    • Convert Sorted Array to Binary Search Tree
    • Symmetric Tree
    • Path Sum
    • Minimum Depth of Binary Tree
    • Binary Tree Preorder Traversal
    • Binary Tree Inorder Traversal
    • Binary Tree Level Order Traversal
    • Binary Tree Level Order Traversal II
    • Minimum Subtree
    • Flatten Binary Tree to Linked List
    • Binary Tree Longest Consecutive Sequence
    • Subtree with Maximum Average
    • Number of Islands
    • Serialize and Deserialize Binary Tree
    • Clone Graph
  • Data Structure
    • Hash Table
    • Bubble Sort
    • Selection Sort
    • Binary Search
    • Merge Sort
    • Binary Tree
    • 递归
    • DFS BFS
    • python技巧
  • two pointers
    • Reverse Vowels of a String
    • Reverse String
    • Remove Duplicates from Sorted Array
    • LeetCode 11. Container With Most Water
    • Strobogrammatic Number
    • Move Zeroes
    • Implement strStr()
  • 哈希表
    • Ransom Note
    • Minimum Index Sum of Two Lists
    • Longest Harmonious Subsequence
    • Untitled
Powered by GitBook
On this page
  • 时间 O(logn)
  • 空间 O(1)

Was this helpful?

  1. Binary Search

Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array wherenum[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 thatnum[-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.

这题一开始看二分法的用法并不明显,可能会不知道从哪里开始找起。我们来分析下给出的东西是否满足二分法执行的条件

  1. 进行二分的数据 - 这个很明显给了

  2. 进行二分的区间: 这个我们如果看题能够发现,第一个和最后一个数是肯定不能够是 peak 的,所以我们的区间就是1 到 length - 2

  3. 要查找的 target - peak 的定义就是num[peak] > num[peak-1] && num[peak] > num[peak+1],那么这个也满足了

  4. 最后就是指针的移动: 这个也就是找一题的考点,我们需要分析可能的情况来看我们的指针应该如何改变

这题我们举个栗子画个图 比如说[1, 2, 1, 3, 4, 5, 7, 6], 画出来的图是长下面这样的。

            /\
          .   \
         / 
        /
       /
 /\   . 
/  \/  
________________________
1 2 1  345  7 6

题目要求找这里面的 peak,也就是这图中的 2 和 7。

那么我们用过仔细的观察,可以发现这图中,任意一个点,可能是以下4种情况

  • /\自己本身就是一个 peak

  • /在一个递增的坡上

    那么我们知道这个点后面肯定有一个 peak,因为题目规定最后一个值是比他前一个值肯定要小的

  • \

    在一个下降的坡上,那么这个点前面肯定有一个 peak

  • \/在一个谷里面, 那么这个时候两边都肯定有 peak,因为要两个 peak 才能形成一个谷。

时间 O(logn)

进行一次二分搜索

空间 O(1)

class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
           # return nums.index(max(nums))
        start, end = 0, len(nums)-1
        while start+1<end:
            mid = (start+end)/2
            if nums[mid] < nums[mid+1]:
                start = mid
            else:
                end = mid
        if nums[start] > nums[start-1] and nums[start]>nums[start+1]:
            return start
        return end
PreviousLongest Increasing SubsequenceNextSearch in Rotated Sorted Array

Last updated 5 years ago

Was this helpful?