Jump game [Leet Code]

Kim Hayeon·2023년 7월 27일
0

Algorithm Study

목록 보기
18/37
post-thumbnail

Problem

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, or false otherwise.

Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: 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

Code

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        tmp = 1
        num = nums[-1]
        flag = False
        if len(nums) < 2:
            return True
        if nums[0] == 0:
            return False
        for i in range(len(nums)-2, -1, -1):
            # print(tmp, num)
            num = nums[i]
            if tmp > num:
                tmp += 1
                flag = False
            else:
                tmp = 1
                flag = True
        return flag
                
            

The other way

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        endPoint = len(nums)-1
        for i in range(len(nums)-2,-1,-1):
            if i + nums[i] >= endPoint:
                endPoint = i
        return endPoint == 0
        

Time Complexity:

Both versions use a single loop that iterates through the elements of the nums list in reverse order. In each iteration, they perform constant-time operations.

Therefore, the time complexity for both versions is O(n), where n is the length of the nums list.

Space Complexity:

First Version (canJump): This version only uses a constant amount of extra space for variables (endPoint, i), so the space complexity is O(1).

Second Version (canJump): This version also uses a constant amount of extra space for variables (tmp, num, flag, i), so the space complexity is O(1).

profile
우리는 무엇이든 될 수 있어

0개의 댓글