55. Jump Game

来源:互联网 发布:mac rstudio xcode 编辑:程序博客网 时间:2024/06/16 11:02

参照:http://www.cnblogs.com/zichi/p/4808025.html
题意:给你一个数组,数组的每个元素表示你能前进的最大步数,最开始时你在第一个元素所在的位置,之后你可以前进,问能不能到达最后一个元素位置(index n-1)。

BFS解法,超时

//bfs    public boolean canJump(int[] nums) {          if (nums.length == 0)            return false;          Set<Integer> flag = new HashSet<Integer>();          Stack<Integer> canReach = new Stack<Integer>();          canReach.push(0);          boolean result = false;          while(canReach.empty() == false){              int p = canReach.pop();              if (p + nums[p] >= nums.length - 1){                  result = true;                  break;              }else{                  for (int i = 1; i <= nums[p]; i ++){                    if (flag.contains(p+i) == false){                        flag.add(p+i);                        canReach.push(p+i);                    }                  }              }          }          return result;    }

O(n)解法:

public boolean canJump(int[] nums) {        int rightMost = 0;        for(int i = 0; i < nums.length; i ++){            if (i > rightMost)  // cannot reach i                break;            if (i + nums[i] > rightMost){                rightMost = i + nums[i];            }        }        return rightMost >= nums.length - 1;    }
0 0
原创粉丝点击