Leetcode 貪心 Jump Game

來源:互聯網
上載者:User

標籤:style   http   color   os   io   ar   for   div   問題   

Jump Game Total Accepted: 18745 Total Submissions: 68916My Submissions

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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.





題意:給一個包含非負整數的數組,每個數表示最大能跳躍的距離,最初的位置在
下標 0處,問能否跳到數組的最後一個位置
思路0:貪心
問能否跳最後一個位置,可以將問題轉換為跳到最後一個位置後剩餘的最大步數(如果不能跳到,提早結束程式)。
通過求到每個位置剩餘的最大步數可求到最後一個位置的剩餘的最大步數。
設 step = A[0],到下一個位置時,step--,並且step = max(step, A[1]);
複雜度:時間O(n),空間O(1)


bool canJump(int A[], int n){if(n == 0) return false;int step = A[0];for(int i = 1; i < n; ++i){if(step <= 0) return false;--step;step = max(step, A[i]);}return true;}


Leetcode 貪心 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.