Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

寻找峰值 #142

Open
yankewei opened this issue Sep 16, 2021 · 1 comment
Open

寻找峰值 #142

yankewei opened this issue Sep 16, 2021 · 1 comment
Labels
中等 题目难度为中等 二分查找 题目包含二分查找解法

Comments

@yankewei
Copy link
Owner

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

给你一个整数数组 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]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-peak-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 中等 题目难度为中等 二分查找 题目包含二分查找解法 labels Sep 16, 2021
@yankewei
Copy link
Owner Author

一次遍历

func findPeakElement(nums []int) int {
    ret := 0
    for i := 0; i < len(nums); i++ {
	if nums[i] > nums[ret] {
	    ret = i
	}
    }
    return ret
}

二分查找

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 二分查找 题目包含二分查找解法
Projects
None yet
Development

No branches or pull requests

1 participant