[leetcode.com]算法题目 - Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

复制代码
 1 class Solution {
 2 public:
 3     bool canJump(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if(1==n) return true;
 7         if(0==n) return false;
 8         
 9         int position = 0;
10         
11         while(position != (n-1)){
12             if(0 == A[position])
13                 return false;
14                 
15             position += A[position];
16             if(position >=n)
17                 return true;
18         }
19         
20         return true;
21     }
22 };
我的答案
复制代码

思路:这道题由于说明了是non-negative integer,唯一到不了终点的情况就是踩到了值为0的点,不能往后走了。总感觉这道题目有问题,如果最后一步迈的特别大,以至于超过了数组的最大脚标,按online judge的意思是可以算作到达的,我原本理解成为了必须正好踩到最后一个位置上才算是到达~总觉得题目有点问题。

posted on   Horstxu  阅读(264)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示