Leetcode 题解系列(七)
来源:互联网 发布:非农数据对原油的影响 编辑:程序博客网 时间:2024/06/06 03:59
45. Jump Game II
题目要求
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Note:
You can assume that you can always reach the last index.
题目分析
贪心算法
最优的一步应当是下一步最远的走法,于是有:
class Solution { public: int jump(vector<int>& nums) { int jumps = 0, curEnd = 0, curFarthest = 0; for (int i = 0; i < nums.size() - 1; i++) { curFarthest = max(curFarthest, i + nums[i]); if (i == curEnd) { jumps++; curEnd = curFarthest; } } return jumps; }};
阅读全文
0 0
- Leetcode 题解系列(七)
- Leetcode 题解系列(一)
- Leetcode 题解系列(二)
- Leetcode 题解系列(三)
- Leetcode 题解系列(四)
- Leetcode 题解系列(五)
- Leetcode 题解系列(六)
- Leetcode 题解系列(八)
- Leetcode 题解系列(九)
- Leetcode 题解系列(十)
- Leetcode 题解系列(十一)
- Leetcode 题解系列(十三)
- Leetcode 题解系列(十二)
- LeetCode OJ题解系列
- LeetCode Single Number系列题解
- LeetCode刷题系列(七)Linked List
- LeetCode题解系列--1. Two Sum
- LeetCode题解系列--5. Longest Palindromic Substring
- 【LeetCode】Binary Tree Zigzag Level Order Traversal 二叉树的锯齿形层次遍历
- Rhyme/ 手写服务器 实现一个基于xml解析的简单的Tomcat服务器
- PTA 7-22 模拟EXCEL排序
- python yield 简单理解
- 配置CISCO IOS
- Leetcode 题解系列(七)
- PTA 7-7 Windows消息队列
- Java中Synchronized的用法
- Coroutine 协同程序
- Dice (III) LightOJ
- 进程调度三种算法的实现(FCFS,SJF,RR)
- 程序员的自我修养(一)-----温故知新
- RGB——三原色到五颜六色
- python @classmethod 的使用场合