当前位置:网站首页>加油站[问题分析->问题转换->贪心]
加油站[问题分析->问题转换->贪心]
2022-07-02 22:07:00 【REN_林森】
前言
很多题需要用到的解法不明显/多种知识点组合,尤其是场景题,那就更需要提取关键问题,并进行分析了。
分析题目的核心需求,需要做适当的知识点联系/组合/改进,才能够完成需求。
一、加油站
二、逻辑分析->贪心
package everyday.greed;
// 加油站
public class CanCompleteCircuit {
/* target:选一个地点开始走,到达每个地点时,可以得到每个地点的油量(都可装,无上限),而没走一步就会耗掉一定油量(可理解为路程量) 可以看看每个位置的油量,应该从可累计油量最大的地方走。 */
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
// 计算每个位置得到的油数和走一步要花费的油数差。
int[] gap = new int[n];
int surplus = 0;// 剩余油量
for (int i = 0; i < n; i++) {
gap[i] = gas[i] - cost[i];
surplus += gap[i];
}
// 只要总得油量 大于等于 总消耗量,那么就一定能找到一个起点,可走一圈,反之则找不到。
// 贪心思维,一条路有负,因为得到量大于等于消耗量,所以剩下半条路和一定为正,且正+负>=0
if (surplus < 0) return -1;
// 双指针找起点。
int begin = 0, sum = 0;
for (int i = 0; i < n; i++) {
if ((sum += gap[i]) < 0) {
begin = i + 1;
sum = 0;
}
}
return begin;
}
}
总结
1)不是所有题就是考察一个明显的知识点,有很多题都是需要分析/挖掘,才能够转换成相关知识点。
2)贪心思想。
参考文献
[1] LeetCode 加油站
边栏推荐
- Unity publishes a method of webgl playing sound
- 电商系统微服务架构
- 540. Single element in ordered array
- [QT] QT multithreading development - reentrancy and thread safety
- Radis:Linux上安装Redis(步骤)
- Market Research - current market situation and future development trend of night vision goggles for pilots
- LxC terminal login method
- Pointer array parameter passing, pointer parameter passing
- 佩服,竟然有人把高等数学这么晦涩难懂的科目,讲解得如此通俗易懂
- I admire that someone explained such an obscure subject as advanced mathematics so easily
猜你喜欢
[001] [arm-cortex-m3/4] internal register
Struct, bit segment, enumeration, union
Based on asp Net (used mobile phone sales management system) +asp Net+c # language +vs2010+ database can be used for course design and post design learning
图形视图框架
Jatpack------LiveData
牛客网:龙与地下城游戏
Socket套接字C/S端流程
Phpcms realizes the direct Alipay payment function of orders
Promise optimized callback hell
[shutter] shutter application theme (themedata | dynamic modification theme)
随机推荐
性能优化----严苛模式
Market Research - current situation and future development trend of herringbone gear Market
[LeetCode] 存在重复元素【217】
电商系统微服务架构
杰理之如何测试按键的误触率【篇】
php优化foreach中的sql查询
PMP项目整合管理
php实现根据输入的年龄查询出生日期符合的数据
Niuke: Dragon and dungeon games
杰理之、产线装配环节【篇】
Pointer - function pointer
杰理之快速触摸不响应问题【篇】
Objects and object variables
[shutter] shutter opens a third-party application (url|launcher plug-in search and installation | url| launcher plug-in official example | open browser | open a third-party application)
【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)
New feature of go1.18: introduce new netip Network Library
Struct, bit segment, enumeration, union
Oracle cursor
Market Research - current market situation and future development trend of marine wet exhaust hose
世界环境日 | 周大福用心服务推动减碳环保