LeetCode 55. Jump Game & 45. Jump Game II題解

55.Jump Game
題目:
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.

Determine if you are able to reach the last index

大意:
給出一個非負整數數組,你最初定位在數組的第一個位置。   
數組中的每個元素代表你在那個位置可以跳躍的最大長度。    
判斷你是否能到達數組的最後一個位置。

思路:
設置最後可到達的位置是max,遍歷數組中的元素。

bool canJump(int* nums, int numsSize) {
    if(numsSize <= 1)
       return true;

    int max = 0;

    for(int i = 0; i < numsSize && i <= max;i++){//i<=max限制是因爲如果max比i小,那麼根本到不了i位置
        if(nums[i]+i > max)
            max = nums[i] + i;
    }

    if(max < numsSize-1)  
        return false;
    return true;
}

45.Jump Game II
和上一題不同是這次要返回最小次數

思路:如果i大於lastReach,這說明上次的跳不夠,所以要再跳一次。

int jump(int* nums, int numsSize) {
    if(numsSize == 0)
        return 0;

    int lastReach = 0,reach = 0,step = 0;
    for(int i = 0;i <= reach && i < numsSize;i++){
        if(i > lastReach){
            step++;
            lastReach = reach;
        }
        if(nums[i] + i > reach)
            reach = nums[i] + i;
    }
    if(reach < numsSize -1)
        return 0;

    return step;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章