# 45. Jump Game II

## 1.問題

* **需要花幾步才能到達最後一格**

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNoh9faEQl7D06ONTkN%2F-LNp04ewveOK75Y9xHgl%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-02%20%E4%B8%8B%E5%8D%889.42.28.png?alt=media\&token=d3cc0c44-313e-46e4-a5ad-3445b4fefe0b)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
* function header, parameter
* test input
* 說明想法
  * 當"當前的索引"大於"上一次所能到達的最遠索引時",  將計數器+1, 並且將"上一次所能到達的最遠索引"更新為"當前所能到達的最遠索引"
  * 每走一步都更新"當前所能到達的最遠索引"
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) {
            return 0 ;
        }
        
        int res = 0, last = 0, curr = 0;
        
        for (int i = 0; i < n; i++) {
            if (i > last) {
                last = curr;
                res++;
            }   
            curr = max(curr, i + nums[i]);
        }
        
        return res;
    }
};
```
