{ "question_id": 55, "question_title": "跳跃游戏", "difficulty": "中等", "question_content": "

给定一个非负整数数组 nums ,你最初位于数组的 第一个下标

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标。

 

示例 1:

输入:nums = [2,3,1,1,4]
输出:
true
解释:
可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。

示例 2:

输入:nums = [3,2,1,0,4]
输出:
false
解释:
无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。

 

提示:

", "topic_link": "https://bbs.csdn.net/topics/600470122", "cpp": "#include \n#include \n#include \nstatic inline int max(int a, int b)\n{\n\treturn a > b ? a : b;\n}\nstatic bool canJump(int *nums, int numsSize)\n{\n\tint i, pos = 0;\n\tfor (i = 0; i < numsSize - 1; i++)\n\t{\n\t\tif (pos < i || pos >= numsSize - 1)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tpos = max(i + nums[i], pos);\n\t}\n\treturn pos >= numsSize - 1;\n}\nint main(int argc, char **argv)\n{\n\tint i, count = argc - 1;\n\tint *nums = malloc(count * sizeof(int));\n\tfor (i = 0; i < count; i++)\n\t{\n\t\tnums[i] = atoi(argv[i + 1]);\n\t}\n\tprintf(\"%s\\n\", canJump(nums, count) ? \"true\" : \"false\");\n\treturn 0;\n}", "java": "class Solution {\n\tpublic boolean canJump(int[] nums) {\n\t\tboolean can = true;\n\t\tif (nums.length < 2) {\n\t\t\treturn can;\n\t\t}\n\t\tint n = nums.length;\n\t\tint stride = 1;\n\t\tfor (int i = n - 2; i >= 0; i--) {\n\t\t\tif (nums[i] < stride) {\n\t\t\t\tstride++;\n\t\t\t\tcan = false;\n\t\t\t} else {\n\t\t\t\tcan = true;\n\t\t\t\tstride = 1;\n\t\t\t}\n\t\t}\n\t\treturn can;\n\t}\n}\n", "js": "", "python": "class Solution(object):\n\tdef canJump(self, nums):\n\t\t\"\"\"\n\t\t:type nums: List[int]\n\t\t:rtype: bool\n\t\t\"\"\"\n\t\tlength = len(nums)\n\t\tbegin = length - 1\n\t\tfor i in reversed(range(length - 1)):\n\t\t\tif i + nums[i] >= begin:\n\t\t\t\tbegin = i\n\t\treturn not begin\n# %%\ns = Solution()\nprint(s.canJump(nums = [2,3,1,1,4]))", "status": 1, "keywords": "贪心,数组,动态规划", "license": { "cpp": "https://github.com/begeekmyfriend/leetcode", "python": "https://github.com/qiyuangong/leetcode", "java": "https://github.com/zhangyu345293721/leetcode" }, "notebook": { "cpp": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/54/54_cpp.ipynb?type=file", "python": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/54/54_python.ipynb?type=file", "java": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/54/54_java.ipynb?type=file" }, "notebook_enable": 1 }