LeetCode 1306. Jump Game III


原题链接在这里:https://leetcode.com/problems/jump-game-iii/

题目:

Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.

Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation: 
All possible ways to reach at index 3 with value 0 are: 
index 5 -> index 4 -> index 1 -> index 3 
index 5 -> index 6 -> index 4 -> index 1 -> index 3 

Example 2:

Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true 
Explanation: 
One possible way to reach at index 3 with value 0 is: 
index 0 -> index 4 -> index 1 -> index 3

Example 3:

Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.

Constraints:

  • 1 <= arr.length <= 5 * 104
  • 0 <= arr[i] < arr.length
  • 0 <= start < arr.length

题解:

Could use either BFS or DFS to check 0 could be reached.

Time Complexity: O(n). n = arr.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public boolean canReach(int[] arr, int start) {
 3         int n = arr.length;
 4         boolean [] visited = new boolean[n];
 5         LinkedList<Integer> que = new LinkedList<>();
 6         que.add(start);
 7         visited[start] = true;
 8         
 9         while(!que.isEmpty()){
10             int cur = que.poll();
11             if(arr[cur] == 0){
12                 return true;
13             }
14             
15             int can1 = cur - arr[cur];
16             if(can1 >= 0 && can1 < n && !visited[can1]){
17                 que.add(can1);
18                 visited[can1] = true;
19             }
20             
21             int can2 = cur + arr[cur];
22             if(can2 >= 0 && can2 < n && !visited[can2]){
23                 que.add(can2);
24                 visited[can2] = true;
25             }
26         }
27         
28         return false;
29     }
30 }

DFS version.

Time Complexity: O(n).

Space: O(n). stack space.

AC Java:

 1 class Solution {
 2     public boolean canReach(int[] arr, int start) {
 3         if(start < 0 || start >= arr.length || arr[start] < 0){
 4             return false;
 5         }
 6         
 7         if(arr[start] == 0){
 8             return true;
 9         }
10         
11         arr[start] = -arr[start];
12         return canReach(arr, start - arr[start]) || canReach(arr, start + arr[start]);
13     }
14 }

类似Jump Game.

原创文章,作者:,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/271291.html

(0)
上一篇 2022年7月3日 09:42
下一篇 2022年7月3日 09:51

相关推荐

发表回复

登录后才能评论