五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(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;

? ? }

}


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

分享到微博請遵守國家法律
瓦房店市| 贡嘎县| 高邑县| 漳州市| 建宁县| 临清市| 沙田区| 徐汇区| 武胜县| 尚志市| 玉溪市| 井冈山市| 大同县| 安顺市| 长治市| 长春市| 怀仁县| 航空| 德庆县| 永年县| 林州市| 丰都县| 柯坪县| 肥东县| 潮安县| 咸阳市| 应城市| 泸定县| 新安县| 汤阴县| 青海省| 博湖县| 长武县| 渝中区| 甘泉县| 中宁县| 会同县| 新津县| 当涂县| 阿合奇县| 瑞金市|