Skip to content

Commit

Permalink
add: 给定油量和消耗量,汽车能否从i出发,回到i位置
Browse files Browse the repository at this point in the history
  • Loading branch information
xldeng committed Nov 10, 2022
1 parent 91b8da8 commit e69bd06
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
23. [找出两个数组的公共元素](https://github.com/dengshasha/algorithm-study/blob/master/array/IntersectionOfTwoArr.js) || [leetcode地址](https://leetcode.com/problems/intersection-of-two-arrays-ii/)
24. [Game of life](https://github.com/dengshasha/algorithm-study/blob/master/array/gameOfLife.js) || [leetcode地址](https://leetcode.com/problems/game-of-life)
25. [找出给定数组的最大乘积的子数组](https://github.com/dengshasha/algorithm-study/blob/master/array/maxProductSubarr.js) || [leetcode地址](https://leetcode.com/problems/maximum-product-subarray/)
26. [给定油量和消耗量,汽车能否从i出发,回到i位置](https://github.com/dengshasha/algorithm-study/blob/master/array/gasStation.js) || [leetcode地址](https://leetcode.com/problems/gas-station/)


### 动态规划
Expand Down
34 changes: 34 additions & 0 deletions array/gasStation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Created by dengxuelian on 2022/11/10
*/
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
* leetcode link: https://leetcode.com/problems/gas-station/
*/
var canCompleteCircuit = function(gas, cost) {
// remain是记录能否完成cycle
// currentRemain是帮助找到索引
let remain = 0, currentRemain = 0;
let index = -1
// 用于标记已经给index赋值的情况
let tag = false
for(let i = 0; i < gas.length; i++) {
let diff = gas[i] - cost[i]
remain += diff
currentRemain += diff;
// 在currentRemain第一次为正值的地方,是可能满足条件的索引(还要结合remain的值)
if(currentRemain >= 0 && !tag) {
index = i;
tag = true
} else if(currentRemain < 0) {
currentRemain = 0;
tag = false
}
}
return remain >= 0 ? index : -1;
};

console.log('3:', canCompleteCircuit([1,2,3,4,5], [3,4,5,1,2]))
console.log('-1:', canCompleteCircuit([2,3,4], [3,4,3]))
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
<title>Document</title>
</head>
<body>
<script src="topologicalSort/courseSchedule.js"></script>
<script src="array/gasStation.js"></script>
</body>
</html>

0 comments on commit e69bd06

Please sign in to comment.