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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

題意:

找到一串數字的山頂元素(最大元素),例如:[1,2,3,1],山頂元素為3

題解:

會有三種情況:

  1. 有山頂:[1,5,2,3,1]=>5
  2. 右偏斜:[4,2,3,1]=>4
  3. 左偏斜:[1,3,2,5,7]=>7
依照以上三種情況來編寫代碼

package LeetCode.Medium;

/*
 * 山峰型,返回山頂數字的index
 * ex:12321
 * return 2
 * ex:12323421
 * return 5
 * 
 * 右偏斜型,返回第0個
 * ex:321
 * return 0
 * 左偏斜型,返回最後一個
 * ex:123
 * return 2
 */
public class FindPeakElement {
    public int findPeakElement(int[] nums) {
        
        boolean isSkew = true;
        int peak_index = 0;
        
        //開始尋找山頂
        for(int i = 1; i < nums.length; i ++) {
            if(i + 1 >= nums.length) {
                break;
            }
            
            //若找到山頂則不是偏斜
            if(nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) {
                peak_index = i;
                isSkew = false;
                break;
            }
        }
        
        //̎處理偏斜的部分
        if(isSkew == true && nums.length > 1) {
            if(nums[0] > nums[1]) {
                peak_index = 0;
            } else if(nums[1] > nums[0]){
                peak_index = nums.length  - 1;
            }
            
        }
        
        return peak_index;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值