Skip to content

Commit 530f379

Browse files
author
haotf
committed
贪心
1 parent ea9fe98 commit 530f379

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

134.加油站.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* @lc app=leetcode.cn id=134 lang=java
3+
*
4+
* [134] 加油站
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public int canCompleteCircuit(int[] gas, int[] cost) {
10+
int sum = 0;
11+
int tank = 0;
12+
int start = 0;
13+
for (int i = 0; i < cost.length; i++) {
14+
sum = sum + gas[i] - cost[i];
15+
tank = tank + gas[i] - cost[i];
16+
if (tank < 0) {
17+
tank = 0;
18+
start = i + 1;
19+
}
20+
}
21+
if (sum < 0 || start == gas.length)
22+
return -1;
23+
return start;
24+
}
25+
}
26+
// @lc code=end

45.跳跃游戏-ii.java

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* @lc app=leetcode.cn id=45 lang=java
3+
*
4+
* [45] 跳跃游戏 II
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public int jump(int[] nums) {
10+
int len = nums.length;
11+
int farthest = 0;
12+
int step = 0;
13+
int point = 0;
14+
15+
for (int i = 0; i < len - 1; i++) {
16+
farthest = Math.max(farthest, i + nums[i]);
17+
if (point == i) {
18+
point = farthest;
19+
step++;
20+
}
21+
}
22+
return step;
23+
}
24+
}
25+
// @lc code=end

55.跳跃游戏.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* @lc app=leetcode.cn id=55 lang=java
3+
*
4+
* [55] 跳跃游戏
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public boolean canJump(int[] nums) {
10+
if (nums.length == 0)
11+
return true;
12+
int len = nums.length;
13+
int farthest = 0;
14+
15+
for (int i = 0; i < len - 1; i++) {
16+
farthest = Math.max(farthest, i + nums[i]);
17+
if (farthest <= i)
18+
return false;
19+
}
20+
21+
return farthest >= len - 1;
22+
}
23+
}
24+
// @lc code=end

0 commit comments

Comments
 (0)