最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

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

? ? }

}


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

分享到微博請遵守國家法律
化德县| 临沂市| 商南县| 高雄县| 鲁甸县| 塔城市| 定远县| 禹州市| 绵竹市| 伊宁市| 常州市| 临泽县| 南通市| 沧州市| 安陆市| 开平市| 平和县| 蛟河市| 兴安县| 虞城县| 垣曲县| 蛟河市| 松桃| 宁蒗| 德昌县| 贵阳市| 若尔盖县| 连江县| 许昌县| 永嘉县| 河南省| 剑河县| 哈密市| 上栗县| 大关县| 赞皇县| 辉南县| 宜黄县| 襄汾县| 建德市| 海宁市|