162. 寻找峰值 中等 二分 一道神奇的题目 多种写法

  1. 寻找峰值
    峰值元素是指其值严格大于左右相邻值的元素。

给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。

你可以假设 nums[-1] = nums[n] = -∞ 。

你必须实现时间复杂度为 O(log n) 的算法来解决此问题。

示例 1:

输入:nums = [1,2,3,1]
输出:2
解释:3 是峰值元素,你的函数应该返回其索引 2。
示例 2:

输入:nums = [1,2,1,3,5,6,4]
输出:1 或 5
解释:你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。

提示:

1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
对于所有有效的 i 都有 nums[i] != nums[i + 1]

普通解法:

当前位置只需要和下一个位置比较
如果是上坡就向右,如果是下坡就向左
直到到达一个峰值
由于两端都是负无穷,不存在边界溢出的问题。

class Solution {
    public int findPeakElement(int[] nums) {
        int n = nums.length;
        int idx = (int) (Math.random() * n);

        while (!(compare(nums, idx - 1, idx) < 0 && compare(nums, idx, idx + 1) > 0)) {
            if (compare(nums, idx, idx + 1) < 0) {
                idx ++;
            } else {
                idx --;
            }
        }
        return idx;
    }

    int compare(int nums[],int a,int b){
    	long x=(a==-1||a==nums.length)?Long.MIN_VALUE:nums[a];
    	long y=(b==-1||b==nums.length)?Long.MIN_VALUE:nums[b];
    	return x>y?1:-1;
    }
}

二分:

为什么可以二分:
首先二分这个算法适用的情况就是存在某种性质使得每次都能够舍弃一半的数据不去考虑

而这道题目里,对于某个点如果确定这点是上坡,需要向右,那么这个点左边的数据是将来都不可能继续访问的,因此可以被丢弃,所以就满足了二分的条件

两种写法:

class Solution {
    public int findPeakElement(int[] nums) {
        int n = nums.length;
        int l=0,r=n-1,idx=0;
        while (!(compare(nums, idx - 1, idx) < 0 && compare(nums, idx, idx + 1) > 0)) {
            if (compare(nums, idx, idx + 1) < 0) {
                l=idx+1;
            } else {
                r=idx-1;
            }
            idx=l+r>>1;
        }
        return idx;
    }

    int compare(int nums[],int a,int b){
    	long x=(a==-1||a==nums.length)?Long.MIN_VALUE:nums[a];
    	long y=(b==-1||b==nums.length)?Long.MIN_VALUE:nums[b];
    	return x>y?1:-1;
    }
}

class Solution {
    public int findPeakElement(int[] nums) {
        int n = nums.length;
        int l=0,r=n-1;
        while(l<=r){
        	int mid=l+r>>1;
        	//if(compare(nums, mid,mid+1)>0&&compare(nums,mid-1,mid)<0)return mid;
        	if(compare(nums, mid, mid+1)<0)l=mid+1;
        	else r=mid-1;
        }
        return l;
    }

    int compare(int nums[],int a,int b){
    	long x=(a==-1||a==nums.length)?Long.MIN_VALUE:nums[a];
    	long y=(b==-1||b==nums.length)?Long.MIN_VALUE:nums[b];
    	return x>y?1:-1;
    }
}

posted @ 2022-11-17 23:01  林动  阅读(5)  评论(0编辑  收藏  举报