提交 0b2efdc7 编写于 作者: L labuladong

fixbug

上级 560ea5d9
......@@ -146,6 +146,8 @@ int helper(vector<int>& memo, int n) {
```cpp
int fib(int N) {
if (N == 0) return 0;
if (N == 1) return 1;
vector<int> dp(N + 1, 0);
// base case
dp[1] = dp[2] = 1;
......@@ -200,7 +202,7 @@ int coinChange(int[] coins, int amount);
比如说 `k = 3`,面值分别为 1,2,5,总金额 `amount = 11`。那么最少需要 3 枚硬币凑出,即 11 = 5 + 5 + 1。
你认为计算机应该如何解决这个问题?显然,就是把所有能的凑硬币方法都穷举出来,然后找找看最少需要多少枚硬币。
你认为计算机应该如何解决这个问题?显然,就是把所有能的凑硬币方法都穷举出来,然后找找看最少需要多少枚硬币。
**1、暴力递归**
......
......@@ -11,7 +11,7 @@
![](../pictures/souyisou.png)
相关推荐:
* [回溯算法解题套路框架](https://labuladong.gitbook.io/algo)
* [回溯算法解题套路框架](https://labuladong.gitbook.io/algo)
* [动态规划解题套路框架](https://labuladong.gitbook.io/algo)
读完本文,你不仅学会了算法套路,还可以顺便去 LeetCode 上拿下如下题目:
......@@ -20,7 +20,7 @@
[503.下一个更大元素II](https://leetcode-cn.com/problems/next-greater-element-ii)
[1118.一月有多少天](https://leetcode-cn.com/problems/number-of-days-in-a-month)
[739.每日温度](https://leetcode-cn.com/problems/daily-temperatures/)
**-----------**
......@@ -82,7 +82,7 @@ vector<int> nextGreaterElement(vector<int>& nums) {
### 问题变形
单调栈的使用技巧差不多了,来一个简单的变形,力扣第 1118 题「一月有多少天」:
单调栈的使用技巧差不多了,来一个简单的变形,力扣第 739 题「每日温度」:
给你一个数组 `T`,这个数组存放的是近几天的天气气温,你返回一个等长的数组,计算:**对于每一天,你还要至少等多少天才能等到一个更暖和的气温;如果等不到那一天,填 0**
......
......@@ -65,7 +65,7 @@ int binarySearch(int[] nums, int target) {
### 一、寻找一个数(基本的二分搜索)
这个场景是最简单的,能也是大家最熟悉的,即搜索一个数,如果存在,返回其索引,否则返回 -1。
这个场景是最简单的,能也是大家最熟悉的,即搜索一个数,如果存在,返回其索引,否则返回 -1。
```java
int binarySearch(int[] nums, int target) {
......@@ -104,7 +104,7 @@ int binarySearch(int[] nums, int target) {
`while(left <= right)` 的终止条件是 `left == right + 1`,写成区间的形式就是 `[right + 1, right]`,或者带个具体的数字进去 `[3, 2]`,可见**这时候区间为空**,因为没有数字既大于等于 3 又小于等于 2 的吧。所以这时候 while 循环终止是正确的,直接返回 -1 即可。
`while(left < right)` 的终止条件是 `left == right`,写成区间的形式就是 `[left, right]`,或者带个具体的数字进去 `[2, 2]`**这时候区间非空**,还有一个数 2,但此时 while 循环终止了。也就是说这区间 `[2, 2]` 被漏掉了,索引 2 没有被搜索,如果这时候直接返回 -1 就是错误的。
`while(left < right)` 的终止条件是 `left == right`,写成区间的形式就是 `[right, right]`,或者带个具体的数字进去 `[2, 2]`**这时候区间非空**,还有一个数 2,但此时 while 循环终止了。也就是说这区间 `[2, 2]` 被漏掉了,索引 2 没有被搜索,如果这时候直接返回 -1 就是错误的。
当然,如果你非要用 `while(left < right)` 也可以,我们已经知道了出错的原因,就打个补丁好了:
......
......@@ -20,7 +20,7 @@
[141.环形链表II](https://leetcode-cn.com/problems/linked-list-cycle-ii)
[167.两数之和 II - 输入有序数组](https://leetcode-cn.com/problems/two-sum)
[167.两数之和 II - 输入有序数组](https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted)
**-----------**
......@@ -80,6 +80,11 @@ ListNode detectCycle(ListNode head) {
if (fast == slow) break;
}
// 上面的代码类似 hasCycle 函数
if (fast == null || fast.next == null) {
// fast 遇到空指针说明没有环
return null;
}
slow = head;
while (slow != fast) {
fast = fast.next;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册