当前位置:网站首页>加油站[问题分析->问题转换->贪心]
加油站[问题分析->问题转换->贪心]
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 加油站
边栏推荐
- Oracle PL / SQL programming
- U++ learning notes - relaxation
- PHP微信抢红包的算法
- 解决 excel 文件上传时更改选中的文件出现错误net::ERR_UPLOAD_FILE_CHANGED
- UE4 UI adaptive screen
- Market Research - current market situation and future development trend of aircraft front wheel steering system
- Market Research - current market situation and future development trend of intravenous injection (IV) bottles
- 杰理之、产线装配环节【篇】
- Storage unit conversion
- 牛客网:最大子矩阵
猜你喜欢

#include errors detected. Please update your includePath.

kubernetes 使用主机名将 pod 分配在指定节点上

数组进阶提高

【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)

Phpcms realizes the direct Alipay payment function of orders

540. Single element in ordered array

Source code analysis - lightweight asynchronous crawler framework Ruia

大话云原生之负载均衡篇-小饭馆客流量变大了

Perceptron model and Application

Build your own website (22)
随机推荐
Simpleitk use - 4 Strange question
Solve the error of changing the selected file when uploading excel file. Net:: err_ UPLOAD_ FILE_ CHANGED
Market Research - current situation and future development trend of environmental friendly fireworks Market
[micro service sentinel] rewrite Sentinel's interface blockexceptionhandler
PHP微信抢红包的算法
【洛谷P1541】乌龟棋【DP】
杰理之快速触摸不响应问题【篇】
Notes on key vocabulary of the original English book biography of jobs (IX) [chapter seven]
Market Research - current situation and future development trend of sickle cell therapy Market
Build your own website (22)
[shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
杰理之样机无触摸,拆机之后重新安装变正常【篇】
U++ learning notes - relaxation
[ODX studio edit PDX] -0.1- how to quickly view the differences in supported diagnostic information between variant variants (service, sub function...)
电商系统微服务架构
Learn computer knowledge from scratch
Market Research - current market situation and future development trend of aircraft wireless intercom system
Task and privilege level protection
【微服务|Sentinel】重写sentinel的接口BlockExceptionHandler
Pointer and string