题目链接

跳跃游戏II

题目描述

image.png

实现代码

思路:由题意可以知道无论怎么走最终都能够走到最后一个下标,因此可以使用贪心算法的思想,每一步都尽量在下一步选择范围内走的最远,如下是反向查找的实现代码:

  1. class Solution {
  2. public int jump(int[] nums) {
  3. int position = nums.length - 1;
  4. int steps = 0;
  5. while (position > 0) {
  6. for (int i = 0; i < position; i++) {
  7. if (i + nums[i] >= position) {
  8. position = i;
  9. steps++;
  10. break;
  11. }
  12. }
  13. }
  14. return steps;
  15. }
  16. }

反向查找代码容易理解,因为使用了两层循环,而我们还可以通过正向查找的方式,将另一层循环得到的数据直接通过变量的形式保存,而减少一层循环,实现代码如下:

  1. class Solution {
  2. public int jump(int[] nums) {
  3. int length = nums.length;
  4. int end = 0;
  5. int maxPosition = 0;
  6. int steps = 0;
  7. for (int i = 0; i < length - 1; i++) {
  8. maxPosition = Math.max(maxPosition, i + nums[i]);
  9. if (i == end) {
  10. end = maxPosition;
  11. steps++;
  12. }
  13. }
  14. return steps;
  15. }
  16. }