Jump Game
LeetCode 55 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Move the goal left whenever i + nums[i] ≥ goal.
ನಾನು Jump Game (LeetCode 55) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Jump / Reachability ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Walk backwards keeping a 'goal' — the leftmost index known to reach the end. Any index that can jump to the goal becomes the new goal. If the goal reaches index 0, the start can make it.
Approach
- 1
goal = last index.
- 2
For i from right to left: if i + nums[i] ≥ goal, goal = i.
- 3
Return goal == 0.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Greedy backward goalPythonO(n) time · O(1) space
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
goal = n-1
i=n-1
while i>=0:
if nums[i]+i>=goal:
goal = i
i-=1
return goal==0Jump Game — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Jump Game ಹಿಂದಿನ intuition ಏನು?
Walk backwards keeping a 'goal' — the leftmost index known to reach the end. Any index that can jump to the goal becomes the new goal. If the goal reaches index 0, the start can make it.
Jump Game (LeetCode 55) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. goal = last index. 2. For i from right to left: if i + nums[i] ≥ goal, goal = i. 3. Return goal == 0.
Jump Game ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Greedy backward goal.)
Jump Game ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
A zero only matters if nothing before it can jump past it.