LeetCode:Jump Game II
2013-09-02 19:52
435 查看
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =
The minimum number of jumps to reach the last index is
(Jump
from index 0 to 1, then
to the last index.)
这题很有意思,算法时间复杂度O(N).
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =
[2,3,1,1,4]
The minimum number of jumps to reach the last index is
2.
(Jump
1step
from index 0 to 1, then
3steps
to the last index.)
这题很有意思,算法时间复杂度O(N).
package leetcode; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.List; public class JumpGameII { static { System.setIn(JumpGameII.class.getResourceAsStream("/data/leetcode/JumpGameII.txt")); } private static StreamTokenizer stdin = new StreamTokenizer(new InputStreamReader(System.in)); private static int readInt() throws IOException { stdin.nextToken(); return (int) stdin.nval; } /** * @param args */ public static void main(String[] args) throws IOException { JumpGameII s = new JumpGameII(); int[] m = new int[5]; for (int i = 0; i < m.length; i++) { m[i] = readInt(); } long start = System.currentTimeMillis(); System.out.println(s.jump(m)); System.out.println("time:" + (System.currentTimeMillis() - start)); } public int jump(int[] A) { int len = A.length; if (len == 0 || len == 1) { return 0; } if (A[0] >= len - 1) { return 1; } List<Integer> list = new ArrayList<Integer>(); list.add(A[0]); int index = 1; int step = 1; while (index < A.length - 1) { while (index > list.get(step - 1)) { step++; } int jump = A[index]; int jumpTo = index + jump; if (jumpTo > list.get(step - 1)) { if (list.size() == step) { list.add(jumpTo); } else { if (jumpTo > list.get(step)) { list.set(step, jumpTo); } } if (jumpTo >= len - 1) { return step + 1; } } index++; } return -1; } }
相关文章推荐
- leetcode Jump Game II
- LeetCode: Jump Game II
- LeetCode 45 Jump Game II(按照数组进行移动)
- LeetCode 47. Jump Game II
- leetcode–jump game II
- [leetcode解题记录]Jump Game和Jump Game II
- Leetcode Jump Game II 解题报告
- LeetCode Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- leetcode——Jump Game II
- 【一天一道LeetCode】#45. Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- [leetcode]Jump Game II
- LeetCode 45 Jump Game II
- LeetCode 55/45 Jump Game I/II-----Greedy**
- [leetcode刷题系列]Jump Game II
- [Leetcode 100] 130 Jump Game II
- leetcode-45. Jump Game II