mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 07:34:06 +00:00
day 19: 55-jump-game
This commit is contained in:
parent
9ad7de8dd5
commit
b8b5318152
9
55-jump-game/driver.cpp
Normal file
9
55-jump-game/driver.cpp
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
#include "soln.hpp"
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
vector<int> nums = {3,2,1,0,4};
|
||||||
|
bool answer = false;
|
||||||
|
Solution soln;
|
||||||
|
cout << "Checked if can jump correctly? " << soln.test(nums, answer) << endl;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
32
55-jump-game/soln.cpp
Normal file
32
55-jump-game/soln.cpp
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
#include "soln.hpp"
|
||||||
|
|
||||||
|
bool Solution::canJump(vector<int> &nums)
|
||||||
|
{
|
||||||
|
int n = nums.size();
|
||||||
|
int cur_pos = n - 2;
|
||||||
|
int gaps = 0;
|
||||||
|
int next_connect = n - 1;
|
||||||
|
// base cases
|
||||||
|
if (n == 1)
|
||||||
|
return true;
|
||||||
|
if (nums[0] == 0)
|
||||||
|
return false;
|
||||||
|
// track last known connection to get to end
|
||||||
|
while (cur_pos >= 0)
|
||||||
|
{
|
||||||
|
if (cur_pos + nums[cur_pos] >= next_connect)
|
||||||
|
{
|
||||||
|
gaps = 0;
|
||||||
|
next_connect = cur_pos;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
gaps++;
|
||||||
|
cur_pos--;
|
||||||
|
}
|
||||||
|
return gaps == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Solution::test(vector<int> &nums, bool answer)
|
||||||
|
{
|
||||||
|
return canJump(nums) == answer;
|
||||||
|
}
|
||||||
7
55-jump-game/soln.hpp
Normal file
7
55-jump-game/soln.hpp
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
#include <bits/stdc++.h>
|
||||||
|
using namespace std;
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool canJump(vector<int>& nums);
|
||||||
|
bool test(vector<int>& nums, bool answer);
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user