問題
原文
You are given an integer array
nums
. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.Return
true
if you can reach the last index, orfalse
otherwise.
Example 1:
123 Input: nums = [2,3,1,1,4]Output: trueExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.Example 2:
123 Input: nums = [3,2,1,0,4]Output: falseExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
内容
あなたには整数の配列 nums が与えられます。あなたは最初、配列の最初のインデックスに位置し、配列の各要素は、その位置でのあなたの最大ジャンプ長を表します。
最後のインデックスに到達できればtrueを、そうでなければfalseを返します。
※正しくない可能性があります。
解答
解答1:Python
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution(object): def canJump(self, nums): #1つ目の要素の値をdistanceに格納 distance = nums[0] #2つ目以降の要素を一巡走査 for i in range(1,len(nums)): #distanceが0の場合、もうジャンプできないのでFalseを返す if distance == 0: return False #現在のdistanceのまま次の要素へ飛んだ場合(distance-1)と、i番目の値の大きい方をdistanceに入れる distance = max(distance-1, nums[i]) #最後まで到達できたらTrueを返す return True |
解答2:
メモ・参考・感想
コメント