[LeetCode] 1306. 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 * 10^4
  • 0 <= arr[i] < arr.length
  • 0 <= start < arr.length

跳跃游戏III。题意是给你一个数组,和一个起点start,是数组中的一个下标,请你返回是否可以经过数次跳跃,到达指定下标的位置。可以往左或者往右跳跃,但是不允许越界。

思路是BFS。这道题跟前两个版本几乎没有任何联系。当你在某一个下标start的时候,因为可以往左也可以往右跳跃,所以需要判断跳跃之后的index是否越界,如果不越界,则放入queue进行下一轮循环。从queue中弹出元素的时候,记得需要判断这个点是否遍历过,如果没有被遍历过,最后也需要加入hashset记录一下。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean canReach(int[] arr, int start) {
 3         int len = arr.length;
 4         HashSet<Integer> visited = new HashSet<>();
 5         Queue<Integer> queue = new LinkedList<>();
 6         queue.offer(start);
 7         while (!queue.isEmpty()) {
 8             int i = queue.poll();
 9             if (arr[i] == 0) {
10                 return true;
11             }
12             if (visited.contains(i)) {
13                 continue;
14             }
15             visited.add(i);
16             if (i + arr[i] < len) {
17                 queue.offer(i + arr[i]);
18             }
19             if (i - arr[i] >= 0) {
20                 queue.offer(i - arr[i]);
21             }
22         }
23         return false;
24     }
25 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13776090.html