博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】55. 跳跃游戏
阅读量:3565 次
发布时间:2019-05-20

本文共 1528 字,大约阅读时间需要 5 分钟。

在这里插入图片描述

解法 1

从左到右遍历数组,假设当 index = x1 时,nums[x1] = 0,则继续向右遍历,直接遇到不为 0 的元素,假设此时 index = x2

且在遍历的时候,记录 index 在 x1 之前的元素,有 maxIndex = index+nums[index](maxIndex 表示下标为 index 对应的元素值所能跨到最远位置)。

如果 maxIndex < x2,则表示从 x1 之前的任一元素位置跳跃,都无法跨过 x2 位置时的 0,因此返回 false。

但是要记住一种特殊情况,假设 maxIndex >= nums.length - 1,则表示已经跳跃到末尾了,此时可以直接返回 true。

public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return false; } int len = nums.length; // 注意 nums[0] 为 0 的特殊情况 if (nums[0] == 0) {
return len == 1; } int index = 0; int lastMax = 0; while (index < len) {
if (nums[index] == 0) {
++index; // 防止越界 while (index < len && nums[index] == 0) {
++index; } if (lastMax < index) {
return false; } } else {
if (index + nums[index] > lastMax) {
lastMax = index + nums[index]; if (lastMax >= len - 1) {
return true; } } ++index; } } return true;}

解法 2

引用自该题目前为止通过的最快解法。

从右到左返回来遍历。

如果有 index = y1,假定 y1 对应的位置能够跳跃到末尾,则只要在 index < y1 的元素中,找到能够跳跃到 y1 位置,或者超越 y1 位置的元素即可。

如果最后能够逆着来到起始位置,则表示成立。

public boolean canJump(int[] nums) {
int leftGood = nums.length - 1; for (int i = nums.length - 2; i >= 0; i--) {
if (i + nums[i] >= leftGood) {
leftGood = i; } } return leftGood == 0;}

上述即贪心算法的实现,具体可以参考 。

转载地址:http://wrerj.baihongyu.com/

你可能感兴趣的文章
redis和memcached有什么区别?
查看>>
Spring中的设计模式
查看>>
如何设计一个秒杀系统 -- 架构原则
查看>>
如何设计一个秒杀系统 -- 动静分离方案
查看>>
JWT 快速了解
查看>>
实习日志一
查看>>
Springboot读取自定义配置文件的几种方法
查看>>
ZigbeeCC2530 --(裸机和协议栈)串口时钟配置
查看>>
ZigBee开发环境搭建 ----IAR for 8051与SmartRFProgram等软件安装使用
查看>>
Python ---太空射击游戏
查看>>
C/C++之struct的小知识
查看>>
温湿度传感器(AM2312)
查看>>
PTA 数据结构与算法题目集(中文)7-47 打印选课学生名单(25 分)vector容器
查看>>
PTA 数据结构与算法题目集(中文) 7-29 修理牧场(25 分)最小堆
查看>>
PTA 数据结构与算法题目集(中文)7-24 树种统计(25 分) map散列表
查看>>
PTA 数据结构与算法题目集(中文)7-26 Windows消息队列(25 分) 最小堆
查看>>
PTA 数据结构与算法题目集(中文)7-45 航空公司VIP客户查询(25 分)map
查看>>
PTA 数据结构与算法题目集(中文) 7-42 整型关键字的散列映射(25 分) 散列表+线性探测法
查看>>
Aizu - ALDS1_1_A Insertion Sort 插入排序
查看>>
Aizu - ALDS1_2_A Bubble Sort 冒泡排序
查看>>