Given an array of non-negative integers nums, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
You can assume that you can always reach the last index.
Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
class Solution {
public int jump(int[] nums) {
if (nums.length == 1){
return 0;
}
if (nums.length == 2){
return 1;
}
return calculation(0, 0, nums);
}
public int calculation(int start, int steps, int[] nums){
int max = 0;
int maxpos = start;
if (start + nums[start] + 1 >= nums.length){
return ++steps;
}
for (int i = 0; i < nums[start]; i++){
int curPos = start + i + 1;
if (curPos < nums.length){
int comp = nums[curPos] + i + start;
if (comp >= max){
max = comp;
maxpos = curPos;
}
} else {
return ++steps;
}
}
steps++;
return calculation(maxpos, steps, nums);
}
}
'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글
AlgoExpert Non-Constructible Change (0) | 2022.07.10 |
---|---|
AlgoExpert Tournament Winner (0) | 2022.07.10 |
LeetCode 189. Rotate Array (0) | 2022.06.18 |
LeetCode 67. Add Binary (0) | 2022.06.14 |
LeetCode 1385. Find the Distance Value Between Two Arrays (0) | 2022.06.10 |