国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

演/貪心/爬坡/二分

2021-09-15 18:18 作者:劍離我離  | 我要投稿

162 尋找峰值

直接貪心

?public?int?findPeakElement(int[]?nums)?{

????????int?idx?=?0;

????????for?(int?i?=?1;?i?<?nums.length;?++i)?{

????????????if?(nums[i]?>?nums[idx])?{

????????????????idx?=?i;

????????????}

????????}

????????return?idx;

????}

遍歷一次保存最大值的下標(biāo)。

方法二:迭代爬坡

class Solution {

? ? public int findPeakElement(int[] nums) {

? ? ? ? int n = nums.length;

? ? ? ? int idx = (int) (Math.random() * n);


? ? ? ? while (!(compare(nums, idx - 1, idx) < 0 && compare(nums, idx, idx + 1) > 0)) {

? ? ? ? ? ? if (compare(nums, idx, idx + 1) < 0) {

? ? ? ? ? ? ? ? idx += 1;

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? idx -= 1;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ??

? ? ? ? return idx;

? ? }


? ? // 輔助函數(shù),輸入下標(biāo) i,返回一個二元組 (0/1, nums[i])

? ? // 方便處理 nums[-1] 以及 nums[n] 的邊界情況

? ? public int[] get(int[] nums, int idx) {

? ? ? ? if (idx == -1 || idx == nums.length) {

? ? ? ? ? ? return new int[]{0, 0};

? ? ? ? }

? ? ? ? return new int[]{1, nums[idx]};

? ? }


? ? public int compare(int[] nums, int idx1, int idx2) {

? ? ? ? int[] num1 = get(nums, idx1);

? ? ? ? int[] num2 = get(nums, idx2);

? ? ? ? if (num1[0] != num2[0]) {

? ? ? ? ? ? return num1[0] > num2[0] ? 1 : -1;

? ? ? ? }

? ? ? ? if (num1[1] == num2[1]) {

? ? ? ? ? ? return 0;

? ? ? ? }

? ? ? ? return num1[1] > num2[1] ? 1 : -1;

? ? }

}


演/貪心/爬坡/二分的評論 (共 條)

分享到微博請遵守國家法律
临江市| 桃园县| 朔州市| 伊吾县| 阳江市| 奇台县| 施甸县| 革吉县| 项城市| 高要市| 巢湖市| 平南县| 辉县市| 克拉玛依市| 精河县| 澄城县| 桃江县| 花莲县| 泰安市| 神木县| 梁平县| 武强县| 武汉市| 巨鹿县| 安泽县| 平潭县| 顺平县| 望江县| 怀宁县| 开远市| 岗巴县| 伊吾县| 芦溪县| 叶城县| 阿克陶县| 射阳县| 缙云县| 竹山县| 山丹县| 清镇市| 莱阳市|