LeetCode-162. Find Peak Element (JAVA)寻找peak元素

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.

迭代

	public int findPeakElement(int[] nums) {
		int lo = 0, hi = nums.length - 1;
		// 等号
		while (lo <= hi) {
			// 无符号右移,忽略符号位,空位都以0补齐
			int mid = (lo + hi) >>> 1;
			// 如果mid-1大,那么peak肯定在lo和mid-1之间(闭区间)
			if (mid - 1 >= 0 &&
					nums[mid] < nums[mid - 1])
				hi = mid - 1;
			// 如果mid+1大,那么peak肯定在mid+1和hi之间(闭区间)
			else if (mid + 1 < nums.length
					&& nums[mid] < nums[mid + 1])
				lo = mid + 1;
			// 其他情况(peak在开头或者结尾,或者中间)
			else
				return mid;
		}
		return -1;
	}

递归

according to the given condition, num[i] != num[i+1], there must exist a O(logN) solution. So we use binary search for this problem.

  • If num[i-1] < num[i] > num[i+1], then num[i] is peak
  • If num[i-1] < num[i] < num[i+1], then num[i+1...n-1] must contains a peak
  • If num[i-1] > num[i] > num[i+1], then num[0...i-1] must contains a peak
  • If num[i-1] > num[i] < num[i+1], then both sides have peak
    (n is num.length)

	public int findPeakElement(int[] num) {
		return helper(num, 0, num.length - 1);
	}

	public int helper(int[] num, int start, int end) {
		// 一个元素
		if (start == end) {
			return start;
			// 两个元素
		} else if (start + 1 == end) {
			if (num[start] > num[end])
				return start;
			return end;
		} else {
			int m = (start + end) / 2;
			// num[i-1] < num[i] > num[i+1], then num[i] is peak
			if (num[m] > num[m - 1] && num[m] > num[m + 1]) {
				return m;
				// num[i-1] < num[i] < num[i+1],
				// then num[i+1...n-1] must contains a peak
			} else if (num[m - 1] > num[m] && num[m] > num[m + 1]) {
				return helper(num, start, m - 1);
			} else {
				// 其他情况
				// 1,num[i-1] > num[i] > num[i+1],
				// then num[0...i-1] must contains a peak
				// 2,num[i-1] > num[i] < num[i+1],
				// then both sides have peak
				// 两边都可以,只需要返回右边即可,题目要求返回一个,
				return helper(num, m + 1, end);
			}

		}
	}

参考:https://discuss.leetcode.com/topic/5848/o-logn-solution-javacode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值