【leetcode】【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.

二、问题分析

这道题最简单的思路就是按照题目的描述,注意边界条件,然后将某个元素与左边和右边的进行比较即可,但这样会比较2n次;还有一种需要利用num[-1] = num[n] = -∞.

三、Java AC 代码

比较2n次

public int findPeakElement(int[] nums) {
        if (nums.length==1) {
			return 0;
		}
		for (int i = 0; i < nums.length; i++) {
			if (i==0) {
				if (nums[0]>nums[1]) {
					return 0;
				}
				continue;
			}
			if (i==nums.length-1) {
				if (nums[i]>nums[i-1]) {
					return nums.length-1;
				}
				break;
			}
			if (nums[i]>nums[i-1] && nums[i]>nums[i+1]) {
				return i;
			}
		}
		return -1;
    }
比较n次
public int findPeakElement(int[] nums) {
        for(int i=1;i<nums.length;i++){
            if(nums[i]<nums[i-1])
                return i-1;
        }
        return nums.length-1;
    }


你可能感兴趣的:(java,LeetCode,array)