博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 403. Frog Jump
阅读量:6171 次
发布时间:2019-06-21

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

Problem

A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.

Note:

The number of stones is ≥ 2 and is < 1,100.

Each stone's position will be a non-negative integer < 2^31.
The first stone's position is always 0.
Example 1:

[0,1,3,5,6,8,12,17]There are a total of 8 stones.The first stone at the 0th unit, second stone at the 1st unit,third stone at the 3rd unit, and so on...The last stone at the 17th unit.Return true. The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.

Example 2:

[0,1,2,3,4,8,9,11]Return false. There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.

Solution

class Solution {    public boolean canCross(int[] stones) {        if (stones == null || stones.length < 2) return true;        if (stones[0] != 0 || stones[1] != 1) return false;        Map
> map = new HashMap<>(); for (int stone: stones) { map.put(stone, new HashSet<>()); } map.get(0).add(1); int len = stones.length; for (int stone: stones) { for (int step: map.get(stone)) { if (stone+step == stones[len-1]) return true; Set
nextSet = map.get(stone+step); if (nextSet != null) { if (step-1 > 0) nextSet.add(step-1); nextSet.add(step); nextSet.add(step+1); } } } return false; }}

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

你可能感兴趣的文章
nginx编译及参数详解
查看>>
VMware下PM魔术分区使用教程
查看>>
nslookup错误
查看>>
我的友情链接
查看>>
Supported plattforms
查看>>
做自己喜欢的事情
查看>>
CRM安装(二)
查看>>
Eclipse工具进行Spring开发时,Spring配置文件智能提示需要安装STS插件
查看>>
NSURLCache内存缓存
查看>>
jquery click嵌套 事件重复注册 多次执行的问题
查看>>
Dev GridControl导出
查看>>
开始翻译Windows Phone 8 Development for Absolute Beginners教程
查看>>
Python tablib模块
查看>>
站立会议02
查看>>
Windows和Linux如何使用Java代码实现关闭进程
查看>>
0428继承性 const static
查看>>
第一课:从一个简单的平方根运算学习平方根---【重温数学】
查看>>
NET反射系统
查看>>
Oracle12C本地用户的创建和登录
查看>>
使用JS制作一个鼠标可拖的DIV(一)——鼠标拖动
查看>>