LeetCode 75

Find Peak Element

Problem
LC 162
Topic
Binary Search
File
official75_LC162FindPeakElement.java
Path
pkg5leetcode/official75/official75_LC162FindPeakElement.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC162FindPeakElement.java
Approach
Binary search on slope compare mid and mid+1.
Complexity
Time O(log n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC162FindPeakElement.java
1package pkg5leetcode.official75;2 3/*4 * Find Peak Element | LC 1625 * APPROACH: Binary search on slope compare mid and mid+1.6 * COMPLEXITY: Time O(log n), Space O(1)7 */8public class official75_LC162FindPeakElement {9    static int findPeakElement(int[] nums) {10        int lo = 0, hi = nums.length - 1;11        while (lo < hi) {12            int mid = lo + (hi - lo) / 2;13            if (nums[mid] < nums[mid + 1]) lo = mid + 1;14            else hi = mid;15        }16        return lo;17    }18 19    public static void main(String[] args) {20        check(findPeakElement(new int[]{1,2,3,1}) == 2, "case1");21        check(findPeakElement(new int[]{1,2,1,3,5,6,4}) == 5, "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}