mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
chore: apply suggestions from code review
Co-authored-by: Caeden Perelli-Harris <caedenperelliharris@gmail.com> Co-authored-by: Piotr Idzik <vil02@users.noreply.github.com>
This commit is contained in:
parent
9bbb2fda81
commit
44e4c4716f
@ -39,10 +39,9 @@ namespace greedy_algorithms {
|
|||||||
* @returns true if the index can be reached
|
* @returns true if the index can be reached
|
||||||
* @returns false if the index can NOT be reached
|
* @returns false if the index can NOT be reached
|
||||||
*/
|
*/
|
||||||
template <typename T>
|
bool can_jump(const std::vector<int> &nums) {
|
||||||
bool can_jump(const std::vector<T> &nums) {
|
|
||||||
size_t lastPos = nums.size() - 1;
|
size_t lastPos = nums.size() - 1;
|
||||||
for (int i = nums.size() - 1; i >= 0; i--) {
|
for (size_t i = lastPos; i != static_cast<size_t>(-1); i--) {
|
||||||
if (i + nums[i] >= lastPos) {
|
if (i + nums[i] >= lastPos) {
|
||||||
lastPos = i;
|
lastPos = i;
|
||||||
}
|
}
|
||||||
@ -56,25 +55,11 @@ bool can_jump(const std::vector<T> &nums) {
|
|||||||
* @returns void
|
* @returns void
|
||||||
*/
|
*/
|
||||||
static void test() {
|
static void test() {
|
||||||
// 1st test
|
assert(greedy_algorithms::can_jump(std::vector<int>({4, 3, 1, 0, 5})));
|
||||||
std::vector<int> nums = { 4, 3, 1, 0, 5 };
|
assert(!greedy_algorithms::can_jump(std::vector<int>({3, 2, 1, 0, 4})));
|
||||||
assert(greedy_algorithms::can_jump(nums) == true);
|
assert(greedy_algorithms::can_jump(std::vector<int>({5, 9, 4, 7, 15, 3})));
|
||||||
|
assert(!greedy_algorithms::can_jump(std::vector<int>({1, 0, 5, 8, 12})));
|
||||||
// 2nd test
|
assert(greedy_algorithms::can_jump(std::vector<int>({2, 1, 4, 7})));
|
||||||
nums = { 3, 2, 1, 0, 4 };
|
|
||||||
assert(greedy_algorithms::can_jump(nums) == false);
|
|
||||||
|
|
||||||
// 3rd test
|
|
||||||
nums = { 5, 9, 4, 7, 15, 3 };
|
|
||||||
assert(greedy_algorithms::can_jump(nums) == true);
|
|
||||||
|
|
||||||
// 4th test
|
|
||||||
nums = { 1, 0, 5, 8, 12 };
|
|
||||||
assert(greedy_algorithms::can_jump(nums) == false);
|
|
||||||
|
|
||||||
// 5th test
|
|
||||||
nums = {2, 1, 4, 7};
|
|
||||||
assert(greedy_algorithms::can_jump(nums) == true);
|
|
||||||
|
|
||||||
std::cout << "All tests have successfully passed!\n";
|
std::cout << "All tests have successfully passed!\n";
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user