162. Find Peak Element 一次遍历或二分查找

来源:互联网 发布:儿童医院在线咨询网络 编辑:程序博客网 时间:2024/06/13 03:42

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.

我的思路:找到数组中的一个极大值返回即可。

这个题的O(n)思路比较简单:

class Solution {public:    int findPeakElement(vector<int>& nums) {        int n=nums.size();        int res;        if(n==0||n==1) return 0;        if(nums[0]>nums[1]) return 0;        if(nums[n-1]>nums[n-2]) return n-1;        for(int i=1;i<n-1;i++)        {                        if(nums[i]>nums[i-1]&&nums[i]>nums[i+1])                res=i;        }        return res;    }};

leetcode提供的答案:

(1)循环一遍数组 O(n) 这里的技巧是:只判断nums[i]>nums[i+1]第一个满足的就是极值。如果遍历到最后还没有满足的,说明这是一个递增序列。

下面的三个图说明了这几种情况:

Graph

第一个数比第二个大,直接返回第一个数,不用考虑之后的情况,因为现在已经是一个极大值

Graph

遍历一遍都没有满足的情况,说明是一个递增序列。返回最后一个数。

Graph

前面都没有满足nums[i]>nums[i+1],之后第一个满足的就是极值。

代码如下:

public class Solution {    public int findPeakElement(int[] nums) {        for (int i = 0; i < nums.length - 1; i++) {            if (nums[i] > nums[i + 1])                return i;        }        return nums.length - 1;    }}
(2)二分查找 O\big(log_2(n)\big)O(log2(n))

中的的那个数如果大于下一个数,说明峰值在左边,反之,说明在右边,依次缩小序列长度

下面是递归版本:

public class Solution {    public int findPeakElement(int[] nums) {        return search(nums, 0, nums.length - 1);    }    public int search(int[] nums, int l, int r) {        if (l == r)            return l;        int mid = (l + r) / 2;        if (nums[mid] > nums[mid + 1])            return search(nums, l, mid);        return search(nums, mid + 1, r);    }}

迭代版本:

class Solution {public:    int findPeakElement(vector<int>& nums) {        int n=nums.size();        int l=0;        int r=n-1;        while(l<r)        {            int mid=l+(r-l)/2;            if(nums[mid]>nums[mid+1])                r=mid;//mid值可能就是极大值不能跳过            else                l=mid+1;        }        return l;    }};



原创粉丝点击