您的位置:首页 > 其它

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 =
[2,3,1,1,4]


The minimum number of jumps to reach the last index is
2
.
(Jump
1
step
from index 0 to 1, then
3
steps
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;
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: