贪心也是一个很有意思的专题,能遇到很多神奇的思路。
但这个专题,leetcode也没放Hard,果然是怕这种玄学专题上点难度大家罩不住。那就很快了,直接过
763. Partition Labels[Medium]
思路:将字母串分组,相同字母必须放一组,求能分出的最多组及分组方案。这个直接预处理一下每个字母最后出现的位置,然后按位贪心,将结束为止延伸到每位的最远位置,如果当前子串内所有最远位置都被包进来了,就可以重新开一个新组了
五年前也做过这题,作为一个典型的预处理题型来做了
LeetCodeGOGOGO刷题记04——代码优化(预处理)_leetcode 预处理-CSDN博客
/*
Author Owen_Q
*/
public class LabelsPatitioner {public static List<Integer> partitionLabels(String s) {List<Integer> result = new ArrayList<>();int[] lastPosition = new int[26];int len = s.length();for (int i = 0; i < len; i++) {lastPosition[s.charAt(i) - 'a'] = i;}int st = 0;int en = 0;for (int i = 0; i < len; i++) {en = Math.max(en, lastPosition[s.charAt(i) - 'a']);if (i == en) {result.add(en - st + 1);st = i + 1;}}return result;}
}
55. Jump Game[Medium]
思路:给定一个一位区域,从起点开始,每个位置有一个最远到达距离,判断能否到达终点。
这个没什么说的,直接贪心最远位置即可,如果到不了终点就停
/*
Author Owen_Q
*/
public class JumpGameReachable {public static boolean canJump(int[] nums) {int maxLen = 0;int len = nums.length;for (int i = 0; i < len; i++) {if (i > maxLen) {return false;}maxLen = Math.max(maxLen, i + nums[i]);}return true;}
}
45. Jump Game II[Medium]
思路:和上一题类似,不过这次保证能到终点,求最少要走的步数。
同样是贪心,这次贪每步能走的最远区域。每次贪心,从上次贪心所获得的区域内能走到的最远区域都可以成为本次贪心的结果。最后注意一下,由于题目保证一定能到达终点,且不会走出终点,则终点处一定只能走零步,因此终点不用计入贪心范围,否则会多算一步。
/*
Author Owen_Q
*/
public class JumpGameFast {public static int jump(int[] nums) {int len = nums.length;int en = 0;int maxLen = 0;int step = 0;for (int i = 0; i < len - 1; i++) {maxLen = Math.max(maxLen, i + nums[i]);if (i == en) {step++;en = maxLen;}}return step;}
}
121. Best Time to Buy and Sell Stock[Easy]
思路:最后来看看这个Easy的贪心,也是很好奇,能怎么个Easy程度
股票题,低价买入,高价卖出,给定一段时间的股票价格,求最高收益。那这确实都不用动脑子,维护一下当前位置的最低价格和从最低价格开始买入当天卖出的最高收益即可
/*
Author Owen_Q
*/
public class StockTrader {public static int maxProfit(int[] prices) {int len = prices.length;int maxProfit = 0;int minPrice = prices[0];for (int i = 1; i < len; i++) {maxProfit = Math.max(maxProfit, prices[i] - minPrice);minPrice = Math.min(minPrice, prices[i]);}return maxProfit;}
}
完结撒花