1345.jump-game-iv
Problem
Problem Description
Solution
This problem can use BFS to check, check each level, if already found in last index, then return, after each level, jumps+1. here level means 3 possible options to jump. so that we can find the min jump steps.
ways to jump from index i
: 1. i + 1, if i + 1 < len && i + 1
index not visited before 2. i - 1
, if i - 1 >= 0
&& i - 1
index not visited before. 3. different indexes which has the same value as value in index i
.
Idea is to using Map to store element and corresponding indexes as key, value pair.
Queue to store each level indexes can jumped into from index i
:
first check curr index
i == len - 1 (last index)
if yes, terminate process, return jumps.
if not, continue
add
i + 1
if meet requirement, and mark as visited.add
i - 1
if meet requirement, and mark as visitedadd
map.get(arr[i])
-- the list of indexes if meet requirement, and mark visited. since it is already visited all indexes, then remove current element from map to avoid unnecessary visit.after each level, jumps+1
For example:
Complexity Analysis
Time Complexity:
O(n)
Space Complexity:
O(n)
n - n is length of arr
Key Points
Group each size k subarray.
Calculate avg of subarray of size k, compare with threshold
Count increase 1 if meet requirements
Code
Java Code
Last updated