[LeetCode]Jump Game II

来源:互联网 发布:医药行业数据清洗 编辑:程序博客网 时间:2024/04/29 10:23
class Solution {//get the max reachable nextPos at every step O(n)public:int jump(int A[], int n) {// Start typing your C/C++ solution below// DO NOT write int main() functionif(0 == n) return 0;int nowPos = 0;int nextPos = 0;int ans = 0;while (true){if(nextPos >= n-1) break;int maxPos = -1;for (int i = nowPos; i <= nextPos; ++i)maxPos = max(i+A[i], maxPos);nowPos = nextPos;nextPos = maxPos;ans++;}return ans;}};

second time

class Solution {public:    int jump(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int  k = 0;        int start = 0;        int end = 0;        while(end < n-1)        {            int newEnd = INT_MIN;            for(int i = start; i <= end; ++i)                newEnd = max(newEnd, A[i]+i);            if(newEnd == end) return -1;            start = end+1;            end = newEnd;            ++k;        }        return k;    }};


原创粉丝点击