1. 程式人生 > 其它 >2021年10月16日 2021-2022第一學期20212303《網路空間安全專業導論》第四周學習總結

2021年10月16日 2021-2022第一學期20212303《網路空間安全專業導論》第四周學習總結

峰值元素是指其值嚴格大於左右相鄰值的元素。

給你一個整數陣列nums,找到峰值元素並返回其索引。陣列可能包含多個峰值,在這種情況下,返回 任何一個峰值 所在位置即可。

你可以假設nums[-1] = nums[n] = -∞ 。

你必須實現時間複雜度為 O(log n) 的演算法來解決此問題。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-peak-element
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {
    public static int findPeakElement(int[] nums) {
        int n = nums.length;
        int l = 0, r = n - 1, ans = -1;
        while (l <= r) {
            int m = (l + r) >> 1;
            if (compare(nums, m - 1, m) < 0 && compare(nums, m, m + 1) > 0) {
                ans = m;
                return ans;
            } else if (compare(nums, m - 1, m) > 0) {
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return ans;

    }

    private static int compare(int[] nums, int idx1, int idx2) {
        if (idx1 < 0) {
            return -1;
        }

        if (idx2 == nums.length) {
            return 1;
        }

        return Integer.compare(nums[idx1], nums[idx2]);
    }
}
心之所向,素履以往 生如逆旅,一葦以航