leetcode_55題——Jump Game(貪心演算法)

來源:互聯網
上載者:User

標籤:

Jump Game Total Accepted: 43051 Total Submissions: 158263My SubmissionsQuestion Solution 

 

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.

 

Hide Tags Array GreedyHave you met this question in a real interview? Yes     這道題目的意思是問你能否從A【0】跳到A【end】,每一個值是在該處所能跳躍的步數的最大值,    1.我想採用廣度優先搜尋的方法來做,利用隊列將A[i]的位置i壓入之後,將之後從i+1到i+A[i]的的位置都壓進去,再在頭處將i出來,並將i放進set中,之後不要再壓i了結果發現這種廣度優先搜尋的方法還是超出時間限制了
#include<iostream>#include<set>#include<queue>using namespace std;bool canJump(vector<int>& nums) {if(nums.empty())return false;if(nums[0]==0)return false;set<int> temp_set;queue<int> temp_queue;temp_queue.push(0);temp_set.insert(0);int len=nums.size();while(!temp_queue.empty()){int temp_int=temp_queue.front();temp_queue.pop();for (int i=0;i<=nums[temp_int];i++){int next_location=temp_int+i;if(next_location==len-1)return true;if(next_location<len-1){if(temp_set.count(next_location)==0){temp_set.insert(next_location);temp_queue.push(next_location);}}}}return false;}int main(){vector<int> vec;vec.push_back(3);vec.push_back(2);vec.push_back(1);vec.push_back(0);vec.push_back(4);cout<<canJump(vec)<<endl;}

  2. 所以呢我又想到另外一種方法,應該是類似於貪心演算法,先將A【i】所跳的最大位置找到,再從這個位置依次往A【i+1】處遍曆,在這期間找到第二個最大的位置

再重複剛才的過程,在這個中間可以判斷是否能夠跳到最後。

#include<iostream>#include<set>#include<queue>using namespace std;bool canJump(vector<int>& nums) {if(nums.empty())return false;if(nums.size()==1)return true;if(nums[0]==0)return false;int len_nums=nums.size();int max_location=nums[0]+0;if(max_location>=len_nums-1)return true;int max_location0=0;while(1){int temp_max=0;for(int i=max_location;i>max_location0;i--){if(nums[i]+i>=len_nums-1)return true;if(nums[i]+i>temp_max)temp_max=nums[i]+i;}if(temp_max<max_location)return false;max_location0=max_location;max_location=temp_max;}}int main(){vector<int> vec;vec.push_back(3);vec.push_back(2);vec.push_back(1);vec.push_back(0);vec.push_back(4);cout<<canJump(vec)<<endl;}

  

 

leetcode_55題——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.