[알고리즘] LeetCode - Jump Game

2023. 8. 25. 03:52·알고리즘/leet code
 

Jump Game - LeetCode

Can you solve this real interview question? Jump Game - 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

leetcode.com

문제 설명

  • 정수형 배열 nums가 주어진다.
  • 인덱스는 첫 번째 자리부터 시작하며, 배열 nums의 각 수는 해당 위치에서의 최대 점프 길이를 나타낸다.
  • 마지막 인덱스에 도착할 수 있으면 true, 없으면 false를 반환해야 한다.

문제 해결

  • 정수형 변수 dis를 현재 위치에서 가장 멀리 갈 수 있는 위치의 값으로 갱신한다.
  • 현재의 위치를 1씩 증가시키면서 dis 보다 작을 때까지 반복해서 최대한 갈 수 있는 거리까지 반복한다.
  • 마지막 인덱스까지 갈 수 있는 경우에는 배열의 크기를 초과하고, 갈 수 없는 경우에는 정수형 변수 now가 마지막 인덱스까지 가지 못하고 반복문에 종료된다.

시간 복잡도

  • O(N)

풀이 코드

class Solution {
    public boolean canJump(int[] nums) {
        int dis = 0;
        int now = 0;
        
        while(now <= dis) {
            dis = Math.max(dis, now + nums[now]);
            if (dis >= nums.length - 1) {
                return true;
            }
            now++;
        }
        return false;
    }
}

결과

시간 메모리
 2 ms 43.9 MB

 

'알고리즘 > leet code' 카테고리의 다른 글

[알고리즘] LeetCode - Two Sum II - Input Array Is Sorted  (0) 2023.08.28
[알고리즘] LeetCode - Valid Palindrome  (0) 2023.08.28
[알고리즘] LeetCode - Best Time to Buy and Sell Stock II  (0) 2023.08.25
[알고리즘] LeetCode - Best Time to Buy and Sell Stock  (0) 2023.08.25
[알고리즘] LeetCode - Rotate Array  (0) 2023.08.25
'알고리즘/leet code' 카테고리의 다른 글
  • [알고리즘] LeetCode - Two Sum II - Input Array Is Sorted
  • [알고리즘] LeetCode - Valid Palindrome
  • [알고리즘] LeetCode - Best Time to Buy and Sell Stock II
  • [알고리즘] LeetCode - Best Time to Buy and Sell Stock
tableMinPark
tableMinPark
Backend Engineer
  • tableMinPark
    Sangmin's Tech Blog
    tableMinPark
  • 전체
    오늘
    어제
  • 블로그 메뉴

    • tech study blog
    • my github
    • monglife github
    • 분류 전체보기 (48)
      • 개발 (7)
        • java (0)
        • kotlin (0)
        • spring boot (0)
        • android (0)
        • junit5 (5)
        • architecture (2)
      • 데브옵스 (3)
        • docker (3)
        • github action (0)
        • grafana (0)
        • prometheus (0)
        • elk (0)
      • 알고리즘 (35)
        • baek joon (0)
        • programmers (4)
        • leet code (29)
      • 일상 (3)
        • Wear OS 앱 개발기 (2)
        • 회고 (1)
  • 태그

    Container
    wear os
    MSA
    java
    volume
    Thread
    docker
    docker compose
    Kotlin
    jetpack-compose
    docker-compose
    micro service
    레이어드 아키텍처
    MVVM
    Android
    20.04
    ubuntu
    synchronized
    apple watch
    monglife
    layered architecture
    mongs
    bind mount
    Galaxy watch
    docker network
  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
tableMinPark
[알고리즘] LeetCode - Jump Game
상단으로

티스토리툴바