162. Find Peak Element

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.

Solution1:Binary Search (Iterative)

思路: if nums[i] > nums[i + 1],为" \ " Pattern,因为左右两边为负无穷,所以此pattern左边肯定含有peak, 则向二分左边部分继续找。else when if nums[i] < nums[i + 1],为" / " Pattern,所以此pattern右边肯定含有peak, 则向二分右边部分继续找。
Time Complexity: O(logN) Space Complexity: O(1)

Solution2:Binary Search (Recursive)

思路: 思路同1的递归写法
Time Complexity: O(logN) Space Complexity: O(1)

Solution3:Binary Search Template

Time Complexity: O(logN) Space Complexity: O(1)

Solution1 Code:

class Solution1 {
    public int findPeakElement(int[] nums) {
        int start = 0, end = nums.length - 1;
        
        while(start < end) {
            int mid1 = (start + end) / 2;
            int mid2 = mid1 + 1;
            
            if(nums[mid1] < nums[mid2]) {
                // found "/" pattern, so the peak must be on the right
                start = mid2;
            }
            else {
                // found "\" pattern, so the peak must be on the left
                end = mid1;
            }
        }
        return start;
    }
}

Solution2 Code:

class Solution2 {
    public int findPeakElement(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }
    
    private int helper(int[] nums, int start, int end) {
        if(start == end) {
            return start;
        }
        else {
            int mid1 = (start + end) / 2;
            int mid2 = mid1 + 1;
            if(nums[mid1] < nums[mid2]) {
                // found "/" pattern, so the peak must be on the right
                return helper(nums, mid2, end);
            }
            else {
                // found "\" pattern, so the peak must be on the left
                return helper(nums, start, mid1);
            }
        }
    }
}

Solution3 Binary Search Template Code:

class Solution {
    public int findPeakElement(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        
        int left = 0, right = nums.length - 1;
        
        while(left + 1 < right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] > nums[mid - 1]) { 
                // "/"
                left = mid;
            }
            else {
                right = mid;
            }
        }
        
        if(nums[left] > nums[right]) {
            return left;
        }
        else {
            return right;
        } 
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容