欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Leetcode 刷题记录 18—— 贪心算法

Leetcode 刷题记录 18—— 贪心算法

2025/6/21 0:26:39 来源:https://blog.csdn.net/lango_LG/article/details/148701616  浏览:    关键词:Leetcode 刷题记录 18—— 贪心算法

本系列为笔者的 Leetcode 刷题记录,顺序为 Hot 100 题官方顺序,根据标签命名,记录笔者总结的做题思路,附部分代码解释和疑问解答,01~07为C++语言,08及以后为Java语言。

01 买卖股票的最佳时机

在这里插入图片描述

在这里插入图片描述

class Solution {public int maxProfit(int[] prices) {int minPrice = prices[0];int ans = 0;for(int i=0; i<prices.length; i++){//最低股票价格minPrice = Math.min(prices[i], minPrice);//当日股票价格 - 最低股票价格 取最大值ans = Math.max(prices[i] - minPrice, ans); }return ans;}
}

02 跳跃游戏

在这里插入图片描述

在这里插入图片描述

class Solution {public boolean canJump(int[] nums) {//只要道路不断延申,人终将走到终点int path = 0;for(int i=0; i<nums.length; i++){if(i > k) return false;k = Math.max(k, i + nums[i]);}return true;}
}

03 跳跃游戏Ⅱ

在这里插入图片描述

在这里插入图片描述

class Solution {public int jump(int[] nums) {int ans = 0, path = 0;int start = 0, end = 1; //初始起跳范围,左闭右开区间while(end < nums.length){for(int i=start; i<end; i++){path = Math.max(path, i + nums[i]);}//更新起跳范围start = end;end = path + 1;ans++;}return ans;}
}

04 划分字母区间

在这里插入图片描述

在这里插入图片描述

class Solution {public List<Integer> partitionLabels(String s) {int[] last = new int[26];int n = s.length();for(int i=0; i<n; i++){last[s.charAt(i) - 'a'] = i; //字母 -> 索引}List<Integer> partition = new LinkedList<>();int start = 0, end = 0;for(int i=0; i<n; i++){end = Math.max(end, last[s.charAt(i) - 'a']);if(end == i){partition.add(end - start + 1);start = end + 1;}}return partition;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词