LeetCode第[55]題(Java):Jump Game

來源:互聯網
上載者:User

標籤:desc   repr   難度   bsp   dex   present   uri   array   class   

題目:跳跳遊戲

難度:Medium

題目內容:

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.

翻譯:

給定一個非負整數數組,您最初被定位在數組的第一個索引中。

數組中的每個元素代表您在該位置的最大跳躍長度。

確定你是否能夠到達最後一個索引。

Example 1:

Input: [2,3,1,1,4]Output: trueExplanation: 第一步,跳2步到索引2,第二步跳1步到索引3,第三步跳1步到索引4,到達
        第一步,跳1步到索引1,第二步跳3步到索引4,到達

Example 2:

Input: [3,2,1,0,4]Output: falseExplanation: 無論如何,你總是會到達索引3。它的最大跳轉長度為0,這使得到達最後一個索引是不可能的。

 

我的思路:不知道咋做。。。

 

 

答案代碼:

1 public boolean canJump(int[] A) {2     int max = 0;3     for(int i=0;i<A.length;i++){4         if(i>max) {return false;}5         max = Math.max(A[i]+i,max);6     }7     return true;8 }

答案思路:因為所跳的步數能從0到A[ i ] 都行所以只要前面能達到的最遠下標的最大值能大於後面的下標,就表示能跳到,否則跳不到。能達到的最遠下標為A[i] + i 。

eg.:[3,2,1,0,4] 

前面三個的能達到的最遠下標最大值為3,所以此時最遠只到下標3,而下標3的最遠下標是自己,到了下標4進行判斷髮現前面的最遠下標比自己的下標小,所以跳不到。

LeetCode第[55]題(Java):Jump Game

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.