Jump Game II(TLE)

 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.)

思路:大数据的TLE,用priority_queue的方法没有解决 

case [25000,24999,24998 ............3,2,1] 直接TLE

class Solution {
public:
    int jump(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> dp(n,INT_MAX);
        dp[0] = 0;
        for(int i = 1; i < n; i++){
            for(int j = 0; j < i; j++){
                if (A[j] >= i - j){
                    dp[i] = min(dp[i],dp[j] + 1);
                }
            }
        }
        return dp[n-1];
    }
    struct Node{
        int jump;
        int idx;
        int value;
        bool operator < (const Node & ls) const{
            return value > ls.value;
        }
    }
    int jump2(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> dp(n,INT_MAX);
        priority_queue<Node> pq();
        dp[0] = 0;
        pq.push(Node(dp[0],0,A[0]));
        for(int i = 1; i < n; i++){
            while(!pq.empty()){
                Node node = pg.top();
                if (A[node.idx] >= i - node.idx){
                    dp[i] = node.jump + 1;
                }else{ //如果长度不够,则可以丢掉,因为将来也不可能用到
                     pg.pop();
                }
            }
            pg.push(dp[i],i,A[i]);
        }
        return dp[n-1];
    }
};

 

posted @ 2013-07-13 17:34  一只会思考的猪  阅读(201)  评论(0编辑  收藏  举报