162. Find Peak Element

复制代码
package LeetCode_162

/**
 * 162. Find Peak Element
 * https://leetcode.com/problems/find-peak-element/description/
 *
 * A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.

Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.

Follow up: Your solution should be in logarithmic complexity.
 * */
class Solution {
    /*
    * solution 1: new array, Time complexity:O(n), Space complexity:O(n)
    * solution 2:binary search, Time complexity:O(logn), Space complexity:O(1)
    * */
    fun findPeakElement(nums: IntArray): Int {
        //solution 1
        //because may imagine that nums[-1] = nums[n] = -∞.
        val newArray = IntArray(nums.size + 2)
        //destPost=1, represent the position that put nums in newArray
        System.arraycopy(nums, 0, newArray, 1, nums.size)
        newArray.set(0,Int.MIN_VALUE)
        newArray.set(newArray.size-1,Int.MIN_VALUE)
        for (i in 1 until newArray.size - 1) {
            if (newArray[i] > newArray[i - 1] && newArray[i] > newArray[i + 1]) {
                return i
            }
        }

        //solution 2:
        var left = 0
        var right = nums.size - 1
        while (left <= right) {
            val mid = left + (right - left) / 2
            if ((mid - 1 < 0 || nums[mid] > nums[mid - 1]) && (mid + 1 >= nums.size || nums[mid] > nums[mid + 1])) {
                return mid
            } else if (nums[mid] < nums[mid + 1]) {
                //find in right side
                left = mid + 1
            } else {
                right = mid - 1
            }
        }
        return 0
    }
}
复制代码

 

posted @   johnny_zhao  阅读(145)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示