[LeetCode][Java] Jump Game II

來源:互聯網
上載者:User

標籤:leetcode   java   jump game ii   

題目:

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


題意:


給定一個非負整數數組,給定的初始化位置在數組的起始位置。

數組中的每個元素代表著你能都在此位置跳躍的最大的距離。

你的目標是用最少的跳躍數達到數組的末尾。

比如:給定A = [2,3,1,1,4]

達到數組尾部的最小的跳躍步數為2。(用1步從索引 0 到 1, 接著用3步到達結尾索引。)


演算法分析:

該題思想主要是,掃描數組,以確定當前最遠能覆蓋的節點,放入maxreach。然後繼續掃描,直到當前的路程超過了上一次算出的覆蓋範圍reach,那麼更新覆蓋範圍,同時更新條數,因為我們是經過了多一跳才能繼續前進的。

形象地說,這個是在爭取每跳最遠的greedy.

    * ret:目前為止的jump數


    * curRch:從A[0]進行ret次jump之後達到的最大範圍


    * curMax:從0~i這i+1個A元素中能達到的最大範圍
    
    * 當curRch < i,說明ret次jump已經不足以覆蓋當前第i個元素,因此需要增加一次jump,使之達到


    * 記錄的curMax。


AC代碼:

/**    * ret:目前為止的jump數    * curRch:從A[0]進行ret次jump之後達到的最大範圍    * curMax:從0~i這i+1個A元素中能達到的最大範圍        * 當curRch < i,說明ret次jump已經不足以覆蓋當前第i個元素,因此需要增加一次jump,使之達到    * 記錄的curMax。        */ public class Solution {public int jump(int[] nums) {        int ret = 0;        int curMax = 0;        int curRch = 0;        for(int i = 0; i < nums.length; i ++)        {            if(curRch < i)            {                ret ++;                curRch = curMax;            }            curMax = Math.max(curMax, nums[i]+i);        }        return ret;    } }



著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Jump Game II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.