# 162. Find Peak Element

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mg65iQs4hPVI5zkzcOH%2F-Mg65xxgFpWDyftTQ2JT%2Fimage.png?alt=media\&token=9aea3a8e-a9ba-4cf7-b0d0-77ef42ca2733)

idea - compare with neighbor

time: O(logn)

space: O(1)

```java
class Solution {
    public int findPeakElement(int[] nums) {
        // 1 2 1 3 1
        // nums[i] != nums[i + 1] for all valid i.
        // why comare your neighbor is the ans?
        
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left)/2;
            if (nums[mid] < nums[mid+1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}
```



## kotlin

```kotlin
class Solution {
    fun findPeakElement(nums: IntArray): Int {
        var left = 0;
        var right = nums.size - 1;
        while (left < right) {
            var mid = left + (right - left)/2;
            if (nums[mid] < nums[mid+1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}
```
