Improved runtime by about 45 ms for leetcode submission

Adjusted start interval from all jumps steps to only jumps height
which exceed the greatest vested index.
This adjustment also removed one addition statement
This commit is contained in:
boolpurist 2024-08-06 13:23:45 +02:00
parent 4b3ff681fe
commit 36ecf4affa

View file

@ -1,8 +1,8 @@
pub struct Solution;
// Copy from here for submitting this solution to leet code
use std::collections::VecDeque;
impl Solution {
pub fn can_jump(nums: Vec<i32>) -> bool {
Solution::idiom_can_jump(&nums)
@ -35,7 +35,7 @@ impl Solution {
// Using a dequeue ensures that every index is visited
let mut next_nodes = VecDeque::from([(0, nums[0])]);
// index visited yet
let mut greatest_visted_indices = -1;
let mut greatest_visited_indices = -1;
if Self::check_with_target_value(target_val, 0) {
return true;
}
@ -45,18 +45,18 @@ impl Solution {
if Self::check_with_target_value(target_val, max_jump_height) {
return true;
}
// It can start at 1 because the every index was checked in previous path walking
for next_to_check in 1..=steps {
let to_add = index + next_to_check;
// Going left to right and using a dequeue
// for subsequent path walking ensures that
// every index before to_add was visited.
if greatest_visted_indices >= to_add {
// already visited this index
continue;
// Going left to right and using a dequeue for FIFO access,
// all indices are visited
let start_point = greatest_visited_indices + 1;
// It can start at greatest_visited_indices + 1 because the every index was checked
// in previous iterations.
// If the max_jump_height is lower than the start_point
// then there is not new index to be discovered
for to_add in start_point..=max_jump_height {
if to_add > greatest_visited_indices {
next_nodes.push_back((to_add, nums[to_add as usize]));
greatest_visited_indices = to_add;
}
greatest_visted_indices = to_add;
next_nodes.push_front((to_add, nums[to_add as usize]));
}
}
false
@ -124,6 +124,41 @@ mod testing {
let expected = true;
assert_case(given, expected);
}
#[test]
// Taken from a failed submission
fn very_complex_cant_jump_complex_array() {
let given = vec![
3, 6, 2, 7, 1, 2, 8, 5, 7, 8, 3, 6, 4, 4, 3, 7, 5, 8, 4, 4, 5, 5, 4, 7, 8, 7, 8, 1, 2,
4, 8, 1, 6, 3, 6, 5, 3, 4, 6, 1, 1, 4, 7, 6, 1, 7, 7, 4, 8, 1, 1, 3, 3, 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