https://leetcode.com/problems/jump-game-ii/description/

 

Jump Game II - LeetCode

Jump Game II - You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0]. Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to

leetcode.com

 

문제

nums[i]의 값만큼 인덱스를 점프해서 마지막 인덱스까지 도달하는 최소한의 점프 값을 구해야 한다.

 

tmp 배열을 하나 만들어서 배열의 인덱스 i 까지 올수 있는 최소한의 점프 수를 저장한다.

배열에 이미 값이 있으면 그 값이 최소값이므로, 이미 있는 값이 0 일때만 tmp[출발한 인덱스]의 값에 +1 해준다.

 

코드

 

package LeetCode;

public class L45 {
    public int jump(int[] nums) {
        int[] tmp = new int[nums.length];

		//tmp 배열 만들기
        for (int i = 0; i < nums.length; i++) {
        	// 인덱스값이 배열의 길이를 넘지 않게 해준다.
            for (int j = 1; j < nums[i] + 1 && (i + j) < nums.length; j++) {
            	// 값이 0일때만 새로운 값 지정하기
                if (tmp[i + j] == 0) tmp[i + j] = tmp[i] + 1;
            }
        }

        return tmp[nums.length - 1];
    }
}

+ Recent posts