> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/ladder_code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/ladder_code/chapter1/find-peak-element.md).

# Find Peak Element

题目：

There is an integer array which has the following features: The numbers in adjacent positions are different. A\[0] < A\[1] && A\[A.length - 2] > A\[A.length - 1]. We define a position P is a peek if: A\[P] > A\[P-1] && A\[P] > A\[P+1] Find a peak element in this array. Return the index of the peak.

分析：

二分让A\[m-1] > A\[m]和A\[m] < A\[m+1]时候移动，剩下情况A\[m-1] \<A\[m] >A\[m+1]就是峰值。

解法：

```
    public int findPeak(int[] A) {
        // write your code here
        if(A.length == 0)
        return -1;

        int s = 1, e = A.length - 2;//起点和终点位置只会在中间

        while(s + 1 < e){
            int m = s + (e - s)/2;

            if(A[m-1] > A[m]){
                e = m;
            }else if(A[m] < A[m+1]){
                s = m;
            }else{
                e = m; //正好是峰值，移动e好保留s
            }
        }

        if(A[s-1] < A[s] && A[s+1] < A[s])
            return s;

        if(A[e-1] < A[e] && A[e+1] < A[e])
            return e;

            return -1;
    }
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://nataliekung.gitbook.io/ladder_code/chapter1/find-peak-element.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
