leetcode 45. Jump Game II

来源:互联网 发布:windows各系统 编辑:程序博客网 时间:2024/05/16 17:27

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

Note:
You can assume that you can always reach the last index.

class Solution {public:    int jump(vector<int>& nums) {        size_t size = nums.size();        if (nums[0] == 0) return 0;        if (size <= 1) return 0;        int ret = 0;        size_t id = 0;        while (id + nums[id] < size - 1) {            size_t maxStep = 0;             size_t tmp = id;            // 剔除nums[id] == 0 的情况;nums[id] >= 1            for (size_t i = 1; i <= nums[id]; ++i) {               if (nums[id + i] != 0 && maxStep < nums[id + i] + id + i) {                   maxStep = nums[id + i] + id + i;                   tmp = id + i;               }            }            // 没有非 0 的元素            if (tmp == id) return 0;            ++ret;            id = tmp;        }        return ++ret;    }};

参考后

class Solution {public:    int jump(vector<int>& nums) {        size_t size = nums.size();        if (size <= 1) return 0;        if (nums[0] == 0) return 0;        int step = 0;        size_t cur = 0;        size_t nextMax = cur + nums[cur];        while (nextMax < size - 1) {            size_t tmp = nextMax;            for (; cur <= nextMax; ++cur) {                if (nums[cur] != 0) tmp = max(tmp, nums[cur] + cur);            }            if (tmp == nextMax) return 0;            ++step;            nextMax = tmp;        }        ++step;        return step;    }};