力扣55:跳跃区间
一个BFS、贪心的题,可以好好研究一下:力扣55跳跃游戏。
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
一开始就用了最普通的暴力BFS,对每个位置,可能的到达的位置都进行入队,然后依次遍历下去,如果nums[i]==0就直接出队,不进行处理。但是这个方法很明显会超时,所以在评论区看到了一个进行了一些优化的BFS,他进行了以下优化:
- 对于出队入队的处理,在while循环内用for循环对队列中已存在的所有元素进行出队和入队的操作。
- 用visited数组处理已经遍历过的位置,避免用contains操作来造成O(n)复杂度的搜索。
class Solution {
public boolean canJump(int[] nums) {
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[nums.length];
q.offer(0);
while(!q.isEmpty()) {
for(int size=q.size();size>0;size--) {
// idx is current position
int idx = q.remove();
// if this condition is true, we can find an answer
if(idx >= nums.length - 1) return true;
// i is the next rightmost position we can reach
for(int i=idx + 1;i < nums.length &&
i<=idx + nums[idx];i++) {
if(visited[i]) continue;
visited[i] = true;
q.offer(i);
}
}
}
return false;
}
}