[LeetCode] Jump Game 跳躍遊戲
阿新 • • 發佈:2019-01-28
宣告:原題目轉載自LeetCode,解答部分為原創
Problem:
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]
true
.
A = [3,2,1,0,4]
, return false
.
思路一:最直接的想法,遍歷一遍陣列nums[] ,假如能夠到達陣列中第 i 個位置,則同樣能到達其後的 nums[i] 個位置,最終只需判斷能到達的位置中有沒有包含最後一個位置即可。該辦法思路簡單,容易實現,但時間複雜度為O(
n ^ 2 )
程式碼如下:
思路二:優化演算法,以達到線性時間複雜度。便歷一遍陣列,對於每個可達到的每個位置 i, 只獲得下一個可到達的最遠點。最終判斷最遠點是否超過終點,若超過,則可到達終點。#include<iostream> #include<vector> using namespace std; class Solution { public: bool canJump(vector<int>& nums) { vector<int> route(nums.size()); //initial assign_value(route, 0, nums.size(), 0); route[0] = 1; for(int i = 0 ; i < nums.size() ; i ++) { if(route[i] == 1) { if(nums[i] > 0) { assign_value(route, i + 1 , i + 1 + nums[i], 1); } } else break; } return route[route.size() - 1]; } private: void assign_value(vector<int> & temp, int begin, int end, int value) { for(int i = begin; i < end; i ++) { temp[i] = value; } } }; int main() { vector<int> nums(5); nums[0] = 2;nums[1] = 3;nums[2] = 1;nums[3] = 1;nums[4] = 4; Solution text_1; if(text_1.canJump(nums)) cout << "True" << endl; else cout << "False" << endl; nums[3] = 0; if(text_1.canJump(nums)) cout << "True" << endl; else cout << "False" << endl; nums[1] = 2; if(text_1.canJump(nums)) cout << "True" << endl; else cout << "False" << endl; return 0; }
程式碼如下:
#include<iostream> #include<vector> using namespace std; class Solution { public: bool canJump(vector<int> & nums) { int reach = 0; for(int i = 0 ; i <= reach && i < nums.size(); i ++) { reach = max(i + nums[i], reach); } if(reach >= nums.size() - 1) return true; else return false; } }; int main() { vector<int> nums(5); nums[0] = 2;nums[1] = 3;nums[2] = 1;nums[3] = 1;nums[4] = 4; Solution text_1; if(text_1.canJump(nums)) cout << "True" << endl; else cout << "False" << endl; nums[3] = 0; if(text_1.canJump(nums)) cout << "True" << endl; else cout << "False" << endl; nums[1] = 2; if(text_1.canJump(nums)) cout << "True" << endl; else cout << "False" << endl; return 0; }