mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -7,7 +7,7 @@
|
||||
|
||||
## 1. 两数之和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/two-sum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/two-sum/)
|
||||
|
||||
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
# 5.最长回文子串
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/longest-palindromic-substring/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/longest-palindromic-substring/)
|
||||
|
||||
给你一个字符串 s,找到 s 中最长的回文子串。
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 第15题. 三数之和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/3sum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/3sum/)
|
||||
|
||||
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
|
||||
|
||||
@ -345,6 +345,76 @@ var threeSum = function(nums) {
|
||||
return res
|
||||
};
|
||||
```
|
||||
|
||||
解法二:nSum通用解法。递归
|
||||
|
||||
```js
|
||||
/**
|
||||
* nsum通用解法,支持2sum,3sum,4sum...等等
|
||||
* 时间复杂度分析:
|
||||
* 1. n = 2时,时间复杂度O(NlogN),排序所消耗的时间。、
|
||||
* 2. n > 2时,时间复杂度为O(N^n-1),即N的n-1次方,至少是2次方,此时可省略排序所消耗的时间。举例:3sum为O(n^2),4sum为O(n^3)
|
||||
* @param {number[]} nums
|
||||
* @return {number[][]}
|
||||
*/
|
||||
var threeSum = function (nums) {
|
||||
// nsum通用解法核心方法
|
||||
function nSumTarget(nums, n, start, target) {
|
||||
// 前提:nums要先排序好
|
||||
let res = [];
|
||||
if (n === 2) {
|
||||
res = towSumTarget(nums, start, target);
|
||||
} else {
|
||||
for (let i = start; i < nums.length; i++) {
|
||||
// 递归求(n - 1)sum
|
||||
let subRes = nSumTarget(
|
||||
nums,
|
||||
n - 1,
|
||||
i + 1,
|
||||
target - nums[i]
|
||||
);
|
||||
for (let j = 0; j < subRes.length; j++) {
|
||||
res.push([nums[i], ...subRes[j]]);
|
||||
}
|
||||
// 跳过相同元素
|
||||
while (nums[i] === nums[i + 1]) i++;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function towSumTarget(nums, start, target) {
|
||||
// 前提:nums要先排序好
|
||||
let res = [];
|
||||
let len = nums.length;
|
||||
let left = start;
|
||||
let right = len - 1;
|
||||
while (left < right) {
|
||||
let sum = nums[left] + nums[right];
|
||||
if (sum < target) {
|
||||
while (nums[left] === nums[left + 1]) left++;
|
||||
left++;
|
||||
} else if (sum > target) {
|
||||
while (nums[right] === nums[right - 1]) right--;
|
||||
right--;
|
||||
} else {
|
||||
// 相等
|
||||
res.push([nums[left], nums[right]]);
|
||||
// 跳过相同元素
|
||||
while (nums[left] === nums[left + 1]) left++;
|
||||
while (nums[right] === nums[right - 1]) right--;
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
nums.sort((a, b) => a - b);
|
||||
// n = 3,此时求3sum之和
|
||||
return nSumTarget(nums, 3, 0, 0);
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
```typescript
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 17.电话号码的字母组合
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/letter-combinations-of-a-phone-number/)
|
||||
|
||||
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 第18题. 四数之和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/4sum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/4sum/)
|
||||
|
||||
题意:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
## 19.删除链表的倒数第N个节点
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/remove-nth-node-from-end-of-list/)
|
||||
|
||||
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
|
||||
|
||||
@ -289,6 +289,30 @@ func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
|
||||
return dummyHead.next
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
function removeNthFromEnd($head, $n) {
|
||||
// 设置虚拟头节点
|
||||
$dummyHead = new ListNode();
|
||||
$dummyHead->next = $head;
|
||||
|
||||
$slow = $fast = $dummyHead;
|
||||
while($n-- && $fast != null){
|
||||
$fast = $fast->next;
|
||||
}
|
||||
// fast 再走一步,让 slow 指向删除节点的上一个节点
|
||||
$fast = $fast->next;
|
||||
while ($fast != NULL) {
|
||||
$fast = $fast->next;
|
||||
$slow = $slow->next;
|
||||
}
|
||||
$slow->next = $slow->next->next;
|
||||
return $dummyHead->next;
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
object Solution {
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 20. 有效的括号
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/valid-parentheses/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/valid-parentheses/)
|
||||
|
||||
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
|
||||
|
||||
@ -400,6 +400,37 @@ bool isValid(char * s){
|
||||
return !stackTop;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
// https://www.php.net/manual/zh/class.splstack.php
|
||||
class Solution
|
||||
{
|
||||
function isValid($s){
|
||||
$stack = new SplStack();
|
||||
for ($i = 0; $i < strlen($s); $i++) {
|
||||
if ($s[$i] == "(") {
|
||||
$stack->push(')');
|
||||
} else if ($s[$i] == "{") {
|
||||
$stack->push('}');
|
||||
} else if ($s[$i] == "[") {
|
||||
$stack->push(']');
|
||||
// 2、遍历匹配过程中,发现栈内没有要匹配的字符 return false
|
||||
// 3、遍历匹配过程中,栈已为空,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
|
||||
} else if ($stack->isEmpty() || $stack->top() != $s[$i]) {
|
||||
return false;
|
||||
} else {//$stack->top() == $s[$i]
|
||||
$stack->pop();
|
||||
}
|
||||
}
|
||||
// 1、遍历完,但是栈不为空,说明有相应的括号没有被匹配,return false
|
||||
return $stack->isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
object Solution {
|
||||
@ -422,5 +453,6 @@ object Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
## 24. 两两交换链表中的节点
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/swap-nodes-in-pairs/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/swap-nodes-in-pairs/)
|
||||
|
||||
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
## 27. 移除元素
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/remove-element/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/remove-element/)
|
||||
|
||||
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 28. 实现 strStr()
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/implement-strstr/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/implement-strstr/)
|
||||
|
||||
实现 strStr() 函数。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 31.下一个排列
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/next-permutation/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/next-permutation/)
|
||||
|
||||
实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
|
||||
|
||||
|
@ -480,6 +480,62 @@ var searchRange = function(nums, target) {
|
||||
return [-1, -1];
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
### TypeScript
|
||||
|
||||
```typescript
|
||||
function searchRange(nums: number[], target: number): number[] {
|
||||
const leftBoard: number = getLeftBorder(nums, target);
|
||||
const rightBoard: number = getRightBorder(nums, target);
|
||||
// target 在nums区间左侧或右侧
|
||||
if (leftBoard === (nums.length - 1) || rightBoard === 0) return [-1, -1];
|
||||
// target 不存在与nums范围内
|
||||
if (rightBoard - leftBoard <= 1) return [-1, -1];
|
||||
// target 存在于nums范围内
|
||||
return [leftBoard + 1, rightBoard - 1];
|
||||
};
|
||||
// 查找第一个大于target的元素下标
|
||||
function getRightBorder(nums: number[], target: number): number {
|
||||
let left: number = 0,
|
||||
right: number = nums.length - 1;
|
||||
// 0表示target在nums区间的左边
|
||||
let rightBoard: number = 0;
|
||||
while (left <= right) {
|
||||
let mid = Math.floor((left + right) / 2);
|
||||
if (nums[mid] <= target) {
|
||||
// 右边界一定在mid右边(不含mid)
|
||||
left = mid + 1;
|
||||
rightBoard = left;
|
||||
} else {
|
||||
// 右边界在mid左边(含mid)
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
return rightBoard;
|
||||
}
|
||||
// 查找第一个小于target的元素下标
|
||||
function getLeftBorder(nums: number[], target: number): number {
|
||||
let left: number = 0,
|
||||
right: number = nums.length - 1;
|
||||
// length-1表示target在nums区间的右边
|
||||
let leftBoard: number = nums.length - 1;
|
||||
while (left <= right) {
|
||||
let mid = Math.floor((left + right) / 2);
|
||||
if (nums[mid] >= target) {
|
||||
// 左边界一定在mid左边(不含mid)
|
||||
right = mid - 1;
|
||||
leftBoard = right;
|
||||
} else {
|
||||
// 左边界在mid右边(含mid)
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
return leftBoard;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Scala
|
||||
```scala
|
||||
object Solution {
|
||||
@ -527,5 +583,6 @@ object Solution {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 35.搜索插入位置
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/search-insert-position/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/search-insert-position/)
|
||||
|
||||
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 37. 解数独
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/sudoku-solver/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/sudoku-solver/)
|
||||
|
||||
编写一个程序,通过填充空格来解决数独问题。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 39. 组合总和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/combination-sum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/combination-sum/)
|
||||
|
||||
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 40.组合总和II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/combination-sum-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/combination-sum-ii/)
|
||||
|
||||
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 42. 接雨水
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/trapping-rain-water/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/trapping-rain-water/)
|
||||
|
||||
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
|
||||
|
||||
@ -744,6 +744,91 @@ var trap = function(height) {
|
||||
};
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
双指针法:
|
||||
|
||||
```typescript
|
||||
function trap(height: number[]): number {
|
||||
const length: number = height.length;
|
||||
let resVal: number = 0;
|
||||
for (let i = 0; i < length; i++) {
|
||||
let leftMaxHeight: number = height[i],
|
||||
rightMaxHeight: number = height[i];
|
||||
let leftIndex: number = i - 1,
|
||||
rightIndex: number = i + 1;
|
||||
while (leftIndex >= 0) {
|
||||
if (height[leftIndex] > leftMaxHeight)
|
||||
leftMaxHeight = height[leftIndex];
|
||||
leftIndex--;
|
||||
}
|
||||
while (rightIndex < length) {
|
||||
if (height[rightIndex] > rightMaxHeight)
|
||||
rightMaxHeight = height[rightIndex];
|
||||
rightIndex++;
|
||||
}
|
||||
resVal += Math.min(leftMaxHeight, rightMaxHeight) - height[i];
|
||||
}
|
||||
return resVal;
|
||||
};
|
||||
```
|
||||
|
||||
动态规划:
|
||||
|
||||
```typescript
|
||||
function trap(height: number[]): number {
|
||||
const length: number = height.length;
|
||||
const leftMaxHeightDp: number[] = [],
|
||||
rightMaxHeightDp: number[] = [];
|
||||
leftMaxHeightDp[0] = height[0];
|
||||
rightMaxHeightDp[length - 1] = height[length - 1];
|
||||
for (let i = 1; i < length; i++) {
|
||||
leftMaxHeightDp[i] = Math.max(height[i], leftMaxHeightDp[i - 1]);
|
||||
}
|
||||
for (let i = length - 2; i >= 0; i--) {
|
||||
rightMaxHeightDp[i] = Math.max(height[i], rightMaxHeightDp[i + 1]);
|
||||
}
|
||||
let resVal: number = 0;
|
||||
for (let i = 0; i < length; i++) {
|
||||
resVal += Math.min(leftMaxHeightDp[i], rightMaxHeightDp[i]) - height[i];
|
||||
}
|
||||
return resVal;
|
||||
};
|
||||
```
|
||||
|
||||
单调栈:
|
||||
|
||||
```typescript
|
||||
function trap(height: number[]): number {
|
||||
const length: number = height.length;
|
||||
const stack: number[] = [];
|
||||
stack.push(0);
|
||||
let resVal: number = 0;
|
||||
for (let i = 1; i < length; i++) {
|
||||
let top = stack[stack.length - 1];
|
||||
if (height[top] > height[i]) {
|
||||
stack.push(i);
|
||||
} else if (height[top] === height[i]) {
|
||||
stack.pop();
|
||||
stack.push(i);
|
||||
} else {
|
||||
while (stack.length > 0 && height[top] < height[i]) {
|
||||
let mid = stack.pop();
|
||||
if (stack.length > 0) {
|
||||
let left = stack[stack.length - 1];
|
||||
let h = Math.min(height[left], height[i]) - height[mid];
|
||||
let w = i - left - 1;
|
||||
resVal += h * w;
|
||||
top = stack[stack.length - 1];
|
||||
}
|
||||
}
|
||||
stack.push(i);
|
||||
}
|
||||
}
|
||||
return resVal;
|
||||
};
|
||||
```
|
||||
|
||||
### C:
|
||||
|
||||
一种更简便的双指针方法:
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 45.跳跃游戏II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/jump-game-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/jump-game-ii/)
|
||||
|
||||
给定一个非负整数数组,你最初位于数组的第一个位置。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 46.全排列
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/permutations/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/permutations/)
|
||||
|
||||
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
|
||||
|
||||
@ -341,7 +341,7 @@ function permute(nums: number[]): number[][] {
|
||||
return resArr;
|
||||
function backTracking(nums: number[], route: number[]): void {
|
||||
if (route.length === nums.length) {
|
||||
resArr.push(route.slice());
|
||||
resArr.push([...route]);
|
||||
return;
|
||||
}
|
||||
let tempVal: number;
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
## 47.全排列 II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/permutations-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/permutations-ii/)
|
||||
|
||||
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
|
||||
|
||||
@ -268,7 +268,7 @@ var permuteUnique = function (nums) {
|
||||
|
||||
function backtracing( used) {
|
||||
if (path.length === nums.length) {
|
||||
result.push(path.slice())
|
||||
result.push([...path])
|
||||
return
|
||||
}
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
@ -303,7 +303,7 @@ function permuteUnique(nums: number[]): number[][] {
|
||||
return resArr;
|
||||
function backTracking(nums: number[], route: number[]): void {
|
||||
if (route.length === nums.length) {
|
||||
resArr.push(route.slice());
|
||||
resArr.push([...route]);
|
||||
return;
|
||||
}
|
||||
for (let i = 0, length = nums.length; i < length; i++) {
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 第51题. N皇后
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/n-queens/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/n-queens/)
|
||||
|
||||
n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
# 52. N皇后II
|
||||
|
||||
题目链接:https://leetcode-cn.com/problems/n-queens-ii/
|
||||
题目链接:https://leetcode.cn/problems/n-queens-ii/
|
||||
|
||||
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
|
||||
|
||||
@ -44,7 +44,7 @@ n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并
|
||||
# 思路
|
||||
|
||||
|
||||
想看:[51.N皇后](https://mp.weixin.qq.com/s/lU_QwCMj6g60nh8m98GAWg) ,基本没有区别
|
||||
详看:[51.N皇后](https://mp.weixin.qq.com/s/lU_QwCMj6g60nh8m98GAWg) ,基本没有区别
|
||||
|
||||
# C++代码
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 53. 最大子序和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/maximum-subarray/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/maximum-subarray/)
|
||||
|
||||
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 53. 最大子序和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/maximum-subarray/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/maximum-subarray/)
|
||||
|
||||
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
## 54.螺旋矩阵
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/spiral-matrix/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/spiral-matrix/)
|
||||
|
||||
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
|
||||
|
||||
@ -128,8 +128,8 @@ public:
|
||||
|
||||
## 类似题目
|
||||
|
||||
* [59.螺旋矩阵II](https://leetcode-cn.com/problems/spiral-matrix-ii/)
|
||||
* [剑指Offer 29.顺时针打印矩阵](https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/)
|
||||
* [59.螺旋矩阵II](https://leetcode.cn/problems/spiral-matrix-ii/)
|
||||
* [剑指Offer 29.顺时针打印矩阵](https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/)
|
||||
|
||||
## 其他语言版本
|
||||
Python:
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 55. 跳跃游戏
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/jump-game/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/jump-game/)
|
||||
|
||||
给定一个非负整数数组,你最初位于数组的第一个位置。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 56. 合并区间
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/merge-intervals/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/merge-intervals/)
|
||||
|
||||
给出一个区间的集合,请合并所有重叠的区间。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
## 59.螺旋矩阵II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/spiral-matrix-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/spiral-matrix-ii/)
|
||||
|
||||
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
|
||||
|
||||
@ -24,6 +24,8 @@
|
||||
|
||||
## 思路
|
||||
|
||||
为了利于录友们理解,我特意录制了视频,[拿下螺旋矩阵,《代码随想录》第五题!](https://www.bilibili.com/video/BV1SL4y1N7mV),结合本篇文章一起看,效果更佳。
|
||||
|
||||
这道题目可以说在面试中出现频率较高的题目,**本题并不涉及到什么算法,就是模拟过程,但却十分考察对代码的掌控能力。**
|
||||
|
||||
要如何画出这个螺旋排列的正方形矩阵呢?
|
||||
@ -74,7 +76,7 @@ public:
|
||||
int loop = n / 2; // 每个圈循环几次,例如n为奇数3,那么loop = 1 只是循环一圈,矩阵中间的值需要单独处理
|
||||
int mid = n / 2; // 矩阵中间的位置,例如:n为3, 中间的位置就是(1,1),n为5,中间位置为(2, 2)
|
||||
int count = 1; // 用来给矩阵中每一个空格赋值
|
||||
int offset = 1; // 每一圈循环,需要控制每一条边遍历的长度
|
||||
int offset = 1; // 需要控制每一条边遍历的长度,每次循环右边界收缩一位
|
||||
int i,j;
|
||||
while (loop --) {
|
||||
i = startx;
|
||||
@ -82,11 +84,11 @@ public:
|
||||
|
||||
// 下面开始的四个for就是模拟转了一圈
|
||||
// 模拟填充上行从左到右(左闭右开)
|
||||
for (j = starty; j < starty + n - offset; j++) {
|
||||
for (j = starty; j < n - offset; j++) {
|
||||
res[startx][j] = count++;
|
||||
}
|
||||
// 模拟填充右列从上到下(左闭右开)
|
||||
for (i = startx; i < startx + n - offset; i++) {
|
||||
for (i = startx; i < n - offset; i++) {
|
||||
res[i][j] = count++;
|
||||
}
|
||||
// 模拟填充下行从右到左(左闭右开)
|
||||
@ -103,7 +105,7 @@ public:
|
||||
starty++;
|
||||
|
||||
// offset 控制每一圈里每一条边遍历的长度
|
||||
offset += 2;
|
||||
offset += 1;
|
||||
}
|
||||
|
||||
// 如果n为奇数的话,需要单独给矩阵最中间的位置赋值
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
# 62.不同路径
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/unique-paths/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/unique-paths/)
|
||||
|
||||
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
# 63. 不同路径 II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/unique-paths-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/unique-paths-ii/)
|
||||
|
||||
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
|
||||
|
||||
|
@ -5,7 +5,7 @@
|
||||
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
|
||||
|
||||
# 70. 爬楼梯
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/climbing-stairs/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/climbing-stairs/)
|
||||
|
||||
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
|
||||
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
## 70. 爬楼梯
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/climbing-stairs/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/climbing-stairs/)
|
||||
|
||||
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 72. 编辑距离
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/edit-distance/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/edit-distance/)
|
||||
|
||||
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 第77题. 组合
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/combinations/ )
|
||||
[力扣题目链接](https://leetcode.cn/problems/combinations/ )
|
||||
|
||||
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
|
||||
|
||||
|
@ -14,7 +14,7 @@
|
||||
|
||||
文中的回溯法是可以剪枝优化的,本篇我们继续来看一下题目77. 组合。
|
||||
|
||||
链接:https://leetcode-cn.com/problems/combinations/
|
||||
链接:https://leetcode.cn/problems/combinations/
|
||||
|
||||
**看本篇之前,需要先看[回溯算法:求组合问题!](https://programmercarl.com/0077.组合.html)**。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 78.子集
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/subsets/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/subsets/)
|
||||
|
||||
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
|
||||
|
||||
@ -260,7 +260,7 @@ var subsets = function(nums) {
|
||||
let result = []
|
||||
let path = []
|
||||
function backtracking(startIndex) {
|
||||
result.push(path.slice())
|
||||
result.push([...path])
|
||||
for(let i = startIndex; i < nums.length; i++) {
|
||||
path.push(nums[i])
|
||||
backtracking(i + 1)
|
||||
@ -280,7 +280,7 @@ function subsets(nums: number[]): number[][] {
|
||||
backTracking(nums, 0, []);
|
||||
return resArr;
|
||||
function backTracking(nums: number[], startIndex: number, route: number[]): void {
|
||||
resArr.push(route.slice());
|
||||
resArr.push([...route]);
|
||||
let length = nums.length;
|
||||
if (startIndex === length) return;
|
||||
for (let i = startIndex; i < length; i++) {
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 84.柱状图中最大的矩形
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/largest-rectangle-in-histogram/)
|
||||
|
||||
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
|
||||
|
||||
@ -486,5 +486,95 @@ var largestRectangleArea = function(heights) {
|
||||
return maxArea;
|
||||
};
|
||||
```
|
||||
TypeScript:
|
||||
|
||||
> 双指针法(会超时):
|
||||
|
||||
```typescript
|
||||
function largestRectangleArea(heights: number[]): number {
|
||||
let resMax: number = 0;
|
||||
for (let i = 0, length = heights.length; i < length; i++) {
|
||||
// 左开右开
|
||||
let left: number = i - 1,
|
||||
right: number = i + 1;
|
||||
while (left >= 0 && heights[left] >= heights[i]) {
|
||||
left--;
|
||||
}
|
||||
while (right < length && heights[right] >= heights[i]) {
|
||||
right++;
|
||||
}
|
||||
resMax = Math.max(resMax, heights[i] * (right - left - 1));
|
||||
}
|
||||
return resMax;
|
||||
};
|
||||
```
|
||||
|
||||
> 动态规划预处理:
|
||||
|
||||
```typescript
|
||||
function largestRectangleArea(heights: number[]): number {
|
||||
const length: number = heights.length;
|
||||
const leftHeightDp: number[] = [],
|
||||
rightHeightDp: number[] = [];
|
||||
leftHeightDp[0] = -1;
|
||||
rightHeightDp[length - 1] = length;
|
||||
for (let i = 1; i < length; i++) {
|
||||
let j = i - 1;
|
||||
while (j >= 0 && heights[i] <= heights[j]) {
|
||||
j = leftHeightDp[j];
|
||||
}
|
||||
leftHeightDp[i] = j;
|
||||
}
|
||||
for (let i = length - 2; i >= 0; i--) {
|
||||
let j = i + 1;
|
||||
while (j < length && heights[i] <= heights[j]) {
|
||||
j = rightHeightDp[j];
|
||||
}
|
||||
rightHeightDp[i] = j;
|
||||
}
|
||||
let resMax: number = 0;
|
||||
for (let i = 0; i < length; i++) {
|
||||
let area = heights[i] * (rightHeightDp[i] - leftHeightDp[i] - 1);
|
||||
resMax = Math.max(resMax, area);
|
||||
}
|
||||
return resMax;
|
||||
};
|
||||
```
|
||||
|
||||
> 单调栈:
|
||||
|
||||
```typescript
|
||||
function largestRectangleArea(heights: number[]): number {
|
||||
heights.push(0);
|
||||
const length: number = heights.length;
|
||||
// 栈底->栈顶:严格单调递增
|
||||
const stack: number[] = [];
|
||||
stack.push(0);
|
||||
let resMax: number = 0;
|
||||
for (let i = 1; i < length; i++) {
|
||||
let top = stack[stack.length - 1];
|
||||
if (heights[top] < heights[i]) {
|
||||
stack.push(i);
|
||||
} else if (heights[top] === heights[i]) {
|
||||
stack.pop();
|
||||
stack.push(i);
|
||||
} else {
|
||||
while (stack.length > 0 && heights[top] > heights[i]) {
|
||||
let mid = stack.pop();
|
||||
let left = stack.length > 0 ? stack[stack.length - 1] : -1;
|
||||
let w = i - left - 1;
|
||||
let h = heights[mid];
|
||||
resMax = Math.max(resMax, w * h);
|
||||
top = stack[stack.length - 1];
|
||||
}
|
||||
stack.push(i);
|
||||
}
|
||||
}
|
||||
return resMax;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
## 90.子集II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/subsets-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/subsets-ii/)
|
||||
|
||||
给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
|
||||
|
||||
@ -299,7 +299,7 @@ var subsetsWithDup = function(nums) {
|
||||
return a - b
|
||||
})
|
||||
function backtracing(startIndex, sortNums) {
|
||||
result.push(path.slice(0))
|
||||
result.push([...path])
|
||||
if(startIndex > nums.length - 1) {
|
||||
return
|
||||
}
|
||||
@ -327,7 +327,7 @@ function subsetsWithDup(nums: number[]): number[][] {
|
||||
backTraking(nums, 0, []);
|
||||
return resArr;
|
||||
function backTraking(nums: number[], startIndex: number, route: number[]): void {
|
||||
resArr.push(route.slice());
|
||||
resArr.push([...route]);
|
||||
let length: number = nums.length;
|
||||
if (startIndex === length) return;
|
||||
for (let i = startIndex; i < length; i++) {
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
# 93.复原IP地址
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/restore-ip-addresses/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/restore-ip-addresses/)
|
||||
|
||||
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
# 96.不同的二叉搜索树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/unique-binary-search-trees/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/unique-binary-search-trees/)
|
||||
|
||||
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 98.验证二叉搜索树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/validate-binary-search-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/validate-binary-search-tree/)
|
||||
|
||||
|
||||
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
|
||||
@ -589,7 +589,50 @@ function isValidBST(root: TreeNode | null): boolean {
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
辅助数组解决:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def isValidBST(root: TreeNode): Boolean = {
|
||||
var arr = new mutable.ArrayBuffer[Int]()
|
||||
// 递归中序遍历二叉树,将节点添加到arr
|
||||
def traversal(node: TreeNode): Unit = {
|
||||
if (node == null) return
|
||||
traversal(node.left)
|
||||
arr.append(node.value)
|
||||
traversal(node.right)
|
||||
}
|
||||
traversal(root)
|
||||
// 这个数组如果是升序就代表是二叉搜索树
|
||||
for (i <- 1 until arr.size) {
|
||||
if (arr(i) <= arr(i - 1)) return false
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
递归中解决:
|
||||
```scala
|
||||
object Solution {
|
||||
def isValidBST(root: TreeNode): Boolean = {
|
||||
var flag = true
|
||||
var preValue:Long = Long.MinValue // 这里要使用Long类型
|
||||
|
||||
def traversal(node: TreeNode): Unit = {
|
||||
if (node == null || flag == false) return
|
||||
traversal(node.left)
|
||||
if (node.value > preValue) preValue = node.value
|
||||
else flag = false
|
||||
traversal(node.right)
|
||||
}
|
||||
traversal(root)
|
||||
flag
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
# 100. 相同的树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/same-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/same-tree/)
|
||||
|
||||
给定两个二叉树,编写一个函数来检验它们是否相同。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 101. 对称二叉树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/symmetric-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/symmetric-tree/)
|
||||
|
||||
给定一个二叉树,检查它是否是镜像对称的。
|
||||
|
||||
|
@ -26,7 +26,7 @@
|
||||
|
||||
# 102.二叉树的层序遍历
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/binary-tree-level-order-traversal/)
|
||||
|
||||
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
|
||||
|
||||
@ -379,7 +379,7 @@ pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
|
||||
|
||||
# 107.二叉树的层次遍历 II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/)
|
||||
|
||||
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
|
||||
|
||||
@ -660,7 +660,7 @@ pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
|
||||
|
||||
# 199.二叉树的右视图
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/binary-tree-right-side-view/)
|
||||
|
||||
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
|
||||
|
||||
@ -907,7 +907,7 @@ object Solution {
|
||||
|
||||
# 637.二叉树的层平均值
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/average-of-levels-in-binary-tree/)
|
||||
|
||||
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
|
||||
|
||||
@ -1163,7 +1163,7 @@ object Solution {
|
||||
|
||||
# 429.N叉树的层序遍历
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/n-ary-tree-level-order-traversal/)
|
||||
|
||||
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
|
||||
|
||||
@ -1434,7 +1434,7 @@ object Solution {
|
||||
|
||||
# 515.在每个树行中找最大值
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/find-largest-value-in-each-tree-row/)
|
||||
|
||||
您需要在二叉树的每一行中找到最大的值。
|
||||
|
||||
@ -1668,7 +1668,7 @@ object Solution {
|
||||
|
||||
# 116.填充每个节点的下一个右侧节点指针
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/)
|
||||
|
||||
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
|
||||
|
||||
@ -1956,7 +1956,7 @@ object Solution {
|
||||
```
|
||||
# 117.填充每个节点的下一个右侧节点指针II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/)
|
||||
|
||||
思路:
|
||||
|
||||
@ -2236,7 +2236,7 @@ object Solution {
|
||||
```
|
||||
# 104.二叉树的最大深度
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/maximum-depth-of-binary-tree/)
|
||||
|
||||
给定一个二叉树,找出其最大深度。
|
||||
|
||||
@ -2477,7 +2477,7 @@ object Solution {
|
||||
|
||||
# 111.二叉树的最小深度
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)
|
||||
|
||||
相对于 104.二叉树的最大深度 ,本题还也可以使用层序遍历的方式来解决,思路是一样的。
|
||||
|
||||
|
@ -12,7 +12,7 @@
|
||||
|
||||
# 104.二叉树的最大深度
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/maximum-depth-of-binary-tree/)
|
||||
|
||||
给定一个二叉树,找出其最大深度。
|
||||
|
||||
@ -223,7 +223,7 @@ impl Solution {
|
||||
|
||||
# 559.n叉树的最大深度
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/maximum-depth-of-n-ary-tree/)
|
||||
|
||||
给定一个 n 叉树,找到其最大深度。
|
||||
|
||||
@ -495,7 +495,7 @@ class solution:
|
||||
|
||||
|
||||
## go
|
||||
|
||||
### 104.二叉树的最大深度
|
||||
```go
|
||||
/**
|
||||
* definition for a binary tree node.
|
||||
@ -548,6 +548,8 @@ func maxdepth(root *treenode) int {
|
||||
|
||||
## javascript
|
||||
|
||||
### 104.二叉树的最大深度
|
||||
|
||||
```javascript
|
||||
var maxdepth = function(root) {
|
||||
if (root === null) return 0;
|
||||
@ -595,6 +597,8 @@ var maxDepth = function(root) {
|
||||
};
|
||||
```
|
||||
|
||||
### 559.n叉树的最大深度
|
||||
|
||||
N叉树的最大深度 递归写法
|
||||
```js
|
||||
var maxDepth = function(root) {
|
||||
@ -627,9 +631,9 @@ var maxDepth = function(root) {
|
||||
};
|
||||
```
|
||||
|
||||
## TypeScript:
|
||||
## TypeScript
|
||||
|
||||
> 二叉树的最大深度:
|
||||
### 104.二叉树的最大深度
|
||||
|
||||
```typescript
|
||||
// 后续遍历(自下而上)
|
||||
@ -672,7 +676,7 @@ function maxDepth(root: TreeNode | null): number {
|
||||
};
|
||||
```
|
||||
|
||||
> N叉树的最大深度
|
||||
### 559.n叉树的最大深度
|
||||
|
||||
```typescript
|
||||
// 后续遍历(自下而上)
|
||||
@ -702,6 +706,8 @@ function maxDepth(root: TreeNode | null): number {
|
||||
|
||||
## C
|
||||
|
||||
### 104.二叉树的最大深度
|
||||
|
||||
二叉树最大深度递归
|
||||
```c
|
||||
int maxDepth(struct TreeNode* root){
|
||||
@ -758,7 +764,8 @@ int maxDepth(struct TreeNode* root){
|
||||
|
||||
## Swift
|
||||
|
||||
>二叉树最大深度
|
||||
### 104.二叉树的最大深度
|
||||
|
||||
```swift
|
||||
// 递归 - 后序
|
||||
func maxDepth1(_ root: TreeNode?) -> Int {
|
||||
@ -797,7 +804,8 @@ func maxDepth(_ root: TreeNode?) -> Int {
|
||||
}
|
||||
```
|
||||
|
||||
>N叉树最大深度
|
||||
### 559.n叉树的最大深度
|
||||
|
||||
```swift
|
||||
// 递归
|
||||
func maxDepth(_ root: Node?) -> Int {
|
||||
@ -833,5 +841,84 @@ func maxDepth1(_ root: Node?) -> Int {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
### 104.二叉树的最大深度
|
||||
递归法:
|
||||
```scala
|
||||
object Solution {
|
||||
def maxDepth(root: TreeNode): Int = {
|
||||
def process(curNode: TreeNode): Int = {
|
||||
if (curNode == null) return 0
|
||||
// 递归左节点和右节点,返回最大的,最后+1
|
||||
math.max(process(curNode.left), process(curNode.right)) + 1
|
||||
}
|
||||
// 调用递归方法,return关键字可以省略
|
||||
process(root)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代法:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def maxDepth(root: TreeNode): Int = {
|
||||
var depth = 0
|
||||
if (root == null) return depth
|
||||
val queue = mutable.Queue[TreeNode]()
|
||||
queue.enqueue(root)
|
||||
while (!queue.isEmpty) {
|
||||
val len = queue.size
|
||||
for (i <- 0 until len) {
|
||||
val curNode = queue.dequeue()
|
||||
if (curNode.left != null) queue.enqueue(curNode.left)
|
||||
if (curNode.right != null) queue.enqueue(curNode.right)
|
||||
}
|
||||
depth += 1 // 只要有层次就+=1
|
||||
}
|
||||
depth
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 559.n叉树的最大深度
|
||||
|
||||
递归法:
|
||||
```scala
|
||||
object Solution {
|
||||
def maxDepth(root: Node): Int = {
|
||||
if (root == null) return 0
|
||||
var depth = 0
|
||||
for (node <- root.children) {
|
||||
depth = math.max(depth, maxDepth(node))
|
||||
}
|
||||
depth + 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代法: (层序遍历)
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def maxDepth(root: Node): Int = {
|
||||
if (root == null) return 0
|
||||
var depth = 0
|
||||
val queue = mutable.Queue[Node]()
|
||||
queue.enqueue(root)
|
||||
while (!queue.isEmpty) {
|
||||
val len = queue.size
|
||||
depth += 1
|
||||
for (i <- 0 until len) {
|
||||
val curNode = queue.dequeue()
|
||||
for (node <- curNode.children) queue.enqueue(node)
|
||||
}
|
||||
}
|
||||
depth
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -12,7 +12,7 @@
|
||||
|
||||
# 106.从中序与后序遍历序列构造二叉树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)
|
||||
|
||||
根据一棵树的中序遍历与后序遍历构造二叉树。
|
||||
|
||||
@ -394,7 +394,7 @@ public:
|
||||
|
||||
# 105.从前序与中序遍历序列构造二叉树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
|
||||
|
||||
根据一棵树的前序遍历与中序遍历构造二叉树。
|
||||
|
||||
@ -1091,7 +1091,53 @@ class Solution_0106 {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
106 从中序与后序遍历序列构造二叉树
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def buildTree(inorder: Array[Int], postorder: Array[Int]): TreeNode = {
|
||||
// 1、如果长度为0,则直接返回null
|
||||
var len = inorder.size
|
||||
if (len == 0) return null
|
||||
// 2、后序数组的最后一个元素是当前根元素
|
||||
var rootValue = postorder(len - 1)
|
||||
var root: TreeNode = new TreeNode(rootValue, null, null)
|
||||
if (len == 1) return root // 如果数组只有一个节点,就直接返回
|
||||
// 3、在中序数组中找到切割点的索引
|
||||
var delimiterIndex: Int = inorder.indexOf(rootValue)
|
||||
// 4、切分数组往下迭代
|
||||
root.left = buildTree(inorder.slice(0, delimiterIndex), postorder.slice(0, delimiterIndex))
|
||||
root.right = buildTree(inorder.slice(delimiterIndex + 1, len), postorder.slice(delimiterIndex, len - 1))
|
||||
root // 返回root,return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
105 从前序与中序遍历序列构造二叉树
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def buildTree(preorder: Array[Int], inorder: Array[Int]): TreeNode = {
|
||||
// 1、如果长度为0,直接返回空
|
||||
var len = inorder.size
|
||||
if (len == 0) return null
|
||||
// 2、前序数组的第一个元素是当前子树根节点
|
||||
var rootValue = preorder(0)
|
||||
var root = new TreeNode(rootValue, null, null)
|
||||
if (len == 1) return root // 如果数组元素只有一个,那么返回根节点
|
||||
// 3、在中序数组中,找到切割点
|
||||
var delimiterIndex = inorder.indexOf(rootValue)
|
||||
|
||||
// 4、切分数组往下迭代
|
||||
root.left = buildTree(preorder.slice(1, delimiterIndex + 1), inorder.slice(0, delimiterIndex))
|
||||
root.right = buildTree(preorder.slice(delimiterIndex + 1, preorder.size), inorder.slice(delimiterIndex + 1, len))
|
||||
|
||||
root
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 108.将有序数组转换为二叉搜索树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/)
|
||||
|
||||
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
|
||||
|
||||
@ -448,5 +448,27 @@ struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def sortedArrayToBST(nums: Array[Int]): TreeNode = {
|
||||
def buildTree(left: Int, right: Int): TreeNode = {
|
||||
if (left > right) return null // 当left大于right的时候,返回空
|
||||
// 最中间的节点是当前节点
|
||||
var mid = left + (right - left) / 2
|
||||
var curNode = new TreeNode(nums(mid))
|
||||
curNode.left = buildTree(left, mid - 1)
|
||||
curNode.right = buildTree(mid + 1, right)
|
||||
curNode
|
||||
}
|
||||
buildTree(0, nums.size - 1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 110.平衡二叉树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/balanced-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/balanced-binary-tree/)
|
||||
|
||||
给定一个二叉树,判断它是否是高度平衡的二叉树。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 111.二叉树的最小深度
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)
|
||||
|
||||
给定一个二叉树,找出其最小深度。
|
||||
|
||||
@ -488,6 +488,46 @@ func minDepth(_ root: TreeNode?) -> Int {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Scala
|
||||
|
||||
递归法:
|
||||
```scala
|
||||
object Solution {
|
||||
def minDepth(root: TreeNode): Int = {
|
||||
if (root == null) return 0
|
||||
if (root.left == null && root.right != null) return 1 + minDepth(root.right)
|
||||
if (root.left != null && root.right == null) return 1 + minDepth(root.left)
|
||||
// 如果两侧都不为空,则取最小值,return关键字可以省略
|
||||
1 + math.min(minDepth(root.left), minDepth(root.right))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代法:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def minDepth(root: TreeNode): Int = {
|
||||
if (root == null) return 0
|
||||
var depth = 0
|
||||
val queue = mutable.Queue[TreeNode]()
|
||||
queue.enqueue(root)
|
||||
while (!queue.isEmpty) {
|
||||
depth += 1
|
||||
val len = queue.size
|
||||
for (i <- 0 until len) {
|
||||
val curNode = queue.dequeue()
|
||||
if (curNode.left != null) queue.enqueue(curNode.left)
|
||||
if (curNode.right != null) queue.enqueue(curNode.right)
|
||||
if (curNode.left == null && curNode.right == null) return depth
|
||||
}
|
||||
}
|
||||
depth
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
rust:
|
||||
```rust
|
||||
impl Solution {
|
||||
@ -550,6 +590,7 @@ impl Solution {
|
||||
}
|
||||
min_depth
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
-----------------------
|
||||
|
@ -16,7 +16,7 @@
|
||||
|
||||
# 112. 路径总和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/path-sum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/path-sum/)
|
||||
|
||||
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
|
||||
|
||||
@ -216,7 +216,7 @@ public:
|
||||
|
||||
# 113. 路径总和ii
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/path-sum-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/path-sum-ii/)
|
||||
|
||||
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
|
||||
|
||||
@ -300,7 +300,7 @@ public:
|
||||
|
||||
## java
|
||||
|
||||
lc112
|
||||
### 0112.路径总和
|
||||
```java
|
||||
class solution {
|
||||
public boolean haspathsum(treenode root, int targetsum) {
|
||||
@ -373,7 +373,7 @@ class solution {
|
||||
|
||||
```
|
||||
|
||||
0113.路径总和-ii
|
||||
### 0113.路径总和-ii
|
||||
|
||||
```java
|
||||
class solution {
|
||||
@ -436,7 +436,7 @@ class Solution {
|
||||
|
||||
## python
|
||||
|
||||
0112.路径总和
|
||||
### 0112.路径总和
|
||||
|
||||
**递归**
|
||||
```python
|
||||
@ -488,7 +488,7 @@ class solution:
|
||||
return false
|
||||
```
|
||||
|
||||
0113.路径总和-ii
|
||||
### 0113.路径总和-ii
|
||||
|
||||
**递归**
|
||||
```python
|
||||
@ -545,7 +545,7 @@ class Solution:
|
||||
|
||||
## go
|
||||
|
||||
112. 路径总和
|
||||
### 112. 路径总和
|
||||
|
||||
```go
|
||||
//递归法
|
||||
@ -570,7 +570,7 @@ func hasPathSum(root *TreeNode, targetSum int) bool {
|
||||
}
|
||||
```
|
||||
|
||||
113. 路径总和 II
|
||||
### 113. 路径总和 II
|
||||
|
||||
```go
|
||||
/**
|
||||
@ -612,7 +612,7 @@ func traverse(node *TreeNode, result *[][]int, currPath *[]int, targetSum int) {
|
||||
|
||||
## javascript
|
||||
|
||||
0112.路径总和
|
||||
### 0112.路径总和
|
||||
|
||||
**递归**
|
||||
```javascript
|
||||
@ -673,7 +673,7 @@ let hasPathSum = function(root, targetSum) {
|
||||
};
|
||||
```
|
||||
|
||||
0113.路径总和-ii
|
||||
### 0113.路径总和-ii
|
||||
|
||||
**递归**
|
||||
```javascript
|
||||
@ -768,7 +768,7 @@ let pathSum = function(root, targetSum) {
|
||||
|
||||
## TypeScript
|
||||
|
||||
> 0112.路径总和
|
||||
### 0112.路径总和
|
||||
|
||||
**递归法:**
|
||||
|
||||
@ -850,7 +850,7 @@ function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
|
||||
};
|
||||
```
|
||||
|
||||
> 0112.路径总和 ii
|
||||
### 0112.路径总和 ii
|
||||
|
||||
**递归法:**
|
||||
|
||||
@ -888,7 +888,7 @@ function pathSum(root: TreeNode | null, targetSum: number): number[][] {
|
||||
|
||||
## Swift
|
||||
|
||||
0112.路径总和
|
||||
### 0112.路径总和
|
||||
|
||||
**递归**
|
||||
|
||||
@ -955,7 +955,7 @@ func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool {
|
||||
}
|
||||
```
|
||||
|
||||
0113.路径总和 II
|
||||
### 0113.路径总和 II
|
||||
|
||||
**递归**
|
||||
|
||||
@ -1126,7 +1126,90 @@ int** pathSum(struct TreeNode* root, int targetSum, int* returnSize, int** retur
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
### 0112.路径总和
|
||||
|
||||
**递归:**
|
||||
```scala
|
||||
object Solution {
|
||||
def hasPathSum(root: TreeNode, targetSum: Int): Boolean = {
|
||||
if(root == null) return false
|
||||
var res = false
|
||||
|
||||
def traversal(curNode: TreeNode, sum: Int): Unit = {
|
||||
if (res) return // 如果直接标记为true了,就没有往下递归的必要了
|
||||
if (curNode.left == null && curNode.right == null && sum == targetSum) {
|
||||
res = true
|
||||
return
|
||||
}
|
||||
// 往下递归
|
||||
if (curNode.left != null) traversal(curNode.left, sum + curNode.left.value)
|
||||
if (curNode.right != null) traversal(curNode.right, sum + curNode.right.value)
|
||||
}
|
||||
|
||||
traversal(root, root.value)
|
||||
res // return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**迭代:**
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def hasPathSum(root: TreeNode, targetSum: Int): Boolean = {
|
||||
if (root == null) return false
|
||||
val stack = mutable.Stack[(TreeNode, Int)]()
|
||||
stack.push((root, root.value)) // 将根节点元素放入stack
|
||||
while (!stack.isEmpty) {
|
||||
val curNode = stack.pop() // 取出栈顶元素
|
||||
// 如果遇到叶子节点,看当前的值是否等于targetSum,等于则返回true
|
||||
if (curNode._1.left == null && curNode._1.right == null && curNode._2 == targetSum) {
|
||||
return true
|
||||
}
|
||||
if (curNode._1.right != null) stack.push((curNode._1.right, curNode._2 + curNode._1.right.value))
|
||||
if (curNode._1.left != null) stack.push((curNode._1.left, curNode._2 + curNode._1.left.value))
|
||||
}
|
||||
false //如果没有返回true,即可返回false,return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 0113.路径总和 II
|
||||
|
||||
**递归:**
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable.ListBuffer
|
||||
def pathSum(root: TreeNode, targetSum: Int): List[List[Int]] = {
|
||||
val res = ListBuffer[List[Int]]()
|
||||
if (root == null) return res.toList
|
||||
val path = ListBuffer[Int]();
|
||||
|
||||
def traversal(cur: TreeNode, count: Int): Unit = {
|
||||
if (cur.left == null && cur.right == null && count == 0) {
|
||||
res.append(path.toList)
|
||||
return
|
||||
}
|
||||
if (cur.left != null) {
|
||||
path.append(cur.left.value)
|
||||
traversal(cur.left, count - cur.left.value)
|
||||
path.remove(path.size - 1)
|
||||
}
|
||||
if (cur.right != null) {
|
||||
path.append(cur.right.value)
|
||||
traversal(cur.right, count - cur.right.value)
|
||||
path.remove(path.size - 1)
|
||||
}
|
||||
}
|
||||
|
||||
path.append(root.value)
|
||||
traversal(root, targetSum - root.value)
|
||||
res.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 115.不同的子序列
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/distinct-subsequences/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/distinct-subsequences/)
|
||||
|
||||
给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 116. 填充每个节点的下一个右侧节点指针
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/)
|
||||
|
||||
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 121. 买卖股票的最佳时机
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/)
|
||||
|
||||
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 122.买卖股票的最佳时机II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/)
|
||||
|
||||
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 122.买卖股票的最佳时机II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/)
|
||||
|
||||
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 123.买卖股票的最佳时机III
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/)
|
||||
|
||||
|
||||
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 127. 单词接龙
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/word-ladder/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/word-ladder/)
|
||||
|
||||
字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:
|
||||
* 序列中第一个单词是 beginWord 。
|
||||
|
@ -5,7 +5,7 @@
|
||||
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
|
||||
# 129. 求根节点到叶节点数字之和
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/sum-root-to-leaf-numbers/)
|
||||
|
||||
# 思路
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 131.分割回文串
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/palindrome-partitioning/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/palindrome-partitioning/)
|
||||
|
||||
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
# 132. 分割回文串 II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/palindrome-partitioning-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/palindrome-partitioning-ii/)
|
||||
|
||||
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 134. 加油站
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/gas-station/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/gas-station/)
|
||||
|
||||
在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 135. 分发糖果
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/candy/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/candy/)
|
||||
|
||||
老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
## 139.单词拆分
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/word-break/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/word-break/)
|
||||
|
||||
给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
|
||||
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
## 142.环形链表II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/linked-list-cycle-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/linked-list-cycle-ii/)
|
||||
|
||||
题意:
|
||||
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
# 150. 逆波兰表达式求值
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/evaluate-reverse-polish-notation/)
|
||||
|
||||
根据 逆波兰表示法,求表达式的值。
|
||||
|
||||
@ -325,6 +325,33 @@ func evalRPN(_ tokens: [String]) -> Int {
|
||||
return stack.last!
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
class Solution {
|
||||
function evalRPN($tokens) {
|
||||
$st = new SplStack();
|
||||
for($i = 0;$i<count($tokens);$i++){
|
||||
// 是数字直接入栈
|
||||
if(is_numeric($tokens[$i])){
|
||||
$st->push($tokens[$i]);
|
||||
}else{
|
||||
// 是符号进行运算
|
||||
$num1 = $st->pop();
|
||||
$num2 = $st->pop();
|
||||
if ($tokens[$i] == "+") $st->push($num2 + $num1);
|
||||
if ($tokens[$i] == "-") $st->push($num2 - $num1);
|
||||
if ($tokens[$i] == "*") $st->push($num2 * $num1);
|
||||
// 注意处理小数部分
|
||||
if ($tokens[$i] == "/") $st->push(intval($num2 / $num1));
|
||||
}
|
||||
}
|
||||
return $st->pop();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
object Solution {
|
||||
@ -351,6 +378,7 @@ object Solution {
|
||||
// 最后返回栈顶,不需要加return关键字
|
||||
stack.pop()
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 151.翻转字符串里的单词
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/reverse-words-in-a-string/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/reverse-words-in-a-string/)
|
||||
|
||||
给定一个字符串,逐个翻转字符串中的每个单词。
|
||||
|
||||
@ -234,7 +234,7 @@ public:
|
||||
}
|
||||
|
||||
void removeExtraSpaces(string& s) {//去除所有空格并在相邻单词之间添加空格, 快慢指针。
|
||||
int slow = 0; //整体思想参考Leetcode: 27. 移除元素:https://leetcode-cn.com/problems/remove-element/
|
||||
int slow = 0; //整体思想参考Leetcode: 27. 移除元素:https://leetcode.cn/problems/remove-element/
|
||||
for (int i = 0; i < s.size(); ++i) { //
|
||||
if (s[i] != ' ') { //遇到非空格就处理,即删除所有空格。
|
||||
if (slow != 0) s[slow++] = ' '; //手动控制空格,给单词之间添加空格。slow != 0说明不是第一个单词,需要在单词前添加空格。
|
||||
@ -817,6 +817,53 @@ object Solution {
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
function reverseWords($s) {
|
||||
$this->removeExtraSpaces($s);
|
||||
$this->reverseString($s, 0, strlen($s)-1);
|
||||
// 将每个单词反转
|
||||
$start = 0;
|
||||
for ($i = 0; $i <= strlen($s); $i++) {
|
||||
// 到达空格或者串尾,说明一个单词结束。进行翻转。
|
||||
if ($i == strlen($s) || $s[$i] == ' ') {
|
||||
// 翻转,注意是左闭右闭 []的翻转。
|
||||
$this->reverseString($s, $start, $i-1);
|
||||
// +1: 单词与单词直接有个空格
|
||||
$start = $i + 1;
|
||||
}
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
|
||||
// 移除多余空格
|
||||
function removeExtraSpaces(&$s){
|
||||
$slow = 0;
|
||||
for ($i = 0; $i < strlen($s); $i++) {
|
||||
if ($s[$i] != ' ') {
|
||||
if ($slow != 0){
|
||||
$s[$slow++] = ' ';
|
||||
}
|
||||
while ($i < strlen($s) && $s[$i] != ' ') {
|
||||
$s[$slow++] = $s[$i++];
|
||||
}
|
||||
}
|
||||
}
|
||||
// 移动覆盖处理,丢弃多余的脏数据。
|
||||
$s = substr($s,0,$slow);
|
||||
return ;
|
||||
}
|
||||
|
||||
// 翻转字符串
|
||||
function reverseString(&$s, $start, $end) {
|
||||
for ($i = $start, $j = $end; $i < $j; $i++, $j--) {
|
||||
$tmp = $s[$i];
|
||||
$s[$i] = $s[$j];
|
||||
$s[$j] = $tmp;
|
||||
}
|
||||
return ;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 188.买卖股票的最佳时机IV
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/)
|
||||
|
||||
给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。
|
||||
|
||||
|
@ -7,6 +7,8 @@
|
||||
|
||||
# 189. 旋转数组
|
||||
|
||||
[力扣题目链接](https://leetcode.cn/problems/rotate-array/)
|
||||
|
||||
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
|
||||
|
||||
进阶:
|
||||
@ -160,6 +162,27 @@ var rotate = function (nums, k) {
|
||||
};
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
|
||||
```typescript
|
||||
function rotate(nums: number[], k: number): void {
|
||||
const length: number = nums.length;
|
||||
k %= length;
|
||||
reverseByRange(nums, 0, length - 1);
|
||||
reverseByRange(nums, 0, k - 1);
|
||||
reverseByRange(nums, k, length - 1);
|
||||
};
|
||||
function reverseByRange(nums: number[], left: number, right: number): void {
|
||||
while (left < right) {
|
||||
const temp = nums[left];
|
||||
nums[left] = nums[right];
|
||||
nums[right] = temp;
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 198.打家劫舍
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/house-robber/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/house-robber/)
|
||||
|
||||
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 第202题. 快乐数
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/happy-number/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/happy-number/)
|
||||
|
||||
编写一个算法来判断一个数 n 是不是快乐数。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 203.移除链表元素
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/remove-linked-list-elements/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/remove-linked-list-elements/)
|
||||
|
||||
题意:删除链表中等于给定值 val 的所有节点。
|
||||
|
||||
@ -28,6 +28,8 @@
|
||||
|
||||
# 思路
|
||||
|
||||
为了方便大家理解,我特意录制了视频:[手把手带你学会操作链表,移除链表元素](https://www.bilibili.com/video/BV18B4y1s7R9),结合视频在看本题解,事半功倍。
|
||||
|
||||
这里以链表 1 4 2 4 来举例,移除元素4。
|
||||
|
||||

|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 205. 同构字符串
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/isomorphic-strings/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/isomorphic-strings/)
|
||||
|
||||
给定两个字符串 s 和 t,判断它们是否是同构的。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 206.反转链表
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/reverse-linked-list/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/reverse-linked-list/)
|
||||
|
||||
题意:反转一个单链表。
|
||||
|
||||
@ -496,8 +496,26 @@ struct ListNode* reverseList(struct ListNode* head){
|
||||
return reverse(NULL, head);
|
||||
}
|
||||
```
|
||||
Scala:
|
||||
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
// 双指针法:
|
||||
function reverseList($head) {
|
||||
$cur = $head;
|
||||
$pre = NULL;
|
||||
while($cur){
|
||||
$temp = $cur->next;
|
||||
$cur->next = $pre;
|
||||
$pre = $cur;
|
||||
$cur = $temp;
|
||||
}
|
||||
return $pre;
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
双指针法:
|
||||
```scala
|
||||
object Solution {
|
||||
@ -529,6 +547,7 @@ object Solution {
|
||||
cur.next = pre
|
||||
reverse(cur, tmp) // 此时cur成为前一个节点,tmp是当前节点
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 209.长度最小的子数组
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/minimum-size-subarray-sum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/minimum-size-subarray-sum/)
|
||||
|
||||
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
|
||||
|
||||
@ -133,8 +133,8 @@ public:
|
||||
|
||||
## 相关题目推荐
|
||||
|
||||
* [904.水果成篮](https://leetcode-cn.com/problems/fruit-into-baskets/)
|
||||
* [76.最小覆盖子串](https://leetcode-cn.com/problems/minimum-window-substring/)
|
||||
* [904.水果成篮](https://leetcode.cn/problems/fruit-into-baskets/)
|
||||
* [76.最小覆盖子串](https://leetcode.cn/problems/minimum-window-substring/)
|
||||
|
||||
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 213.打家劫舍II
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/house-robber-ii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/house-robber-ii/)
|
||||
|
||||
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
|
||||
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
# 216.组合总和III
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/combination-sum-iii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/combination-sum-iii/)
|
||||
|
||||
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 222.完全二叉树的节点个数
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/count-complete-tree-nodes/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/count-complete-tree-nodes/)
|
||||
|
||||
给出一个完全二叉树,求出该树的节点个数。
|
||||
|
||||
@ -646,5 +646,68 @@ func countNodes(_ root: TreeNode?) -> Int {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
```scala
|
||||
object Solution {
|
||||
def countNodes(root: TreeNode): Int = {
|
||||
if(root == null) return 0
|
||||
1 + countNodes(root.left) + countNodes(root.right)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
层序遍历:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def countNodes(root: TreeNode): Int = {
|
||||
if (root == null) return 0
|
||||
val queue = mutable.Queue[TreeNode]()
|
||||
var node = 0
|
||||
queue.enqueue(root)
|
||||
while (!queue.isEmpty) {
|
||||
val len = queue.size
|
||||
for (i <- 0 until len) {
|
||||
node += 1
|
||||
val curNode = queue.dequeue()
|
||||
if (curNode.left != null) queue.enqueue(curNode.left)
|
||||
if (curNode.right != null) queue.enqueue(curNode.right)
|
||||
}
|
||||
}
|
||||
node
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
利用完全二叉树性质:
|
||||
```scala
|
||||
object Solution {
|
||||
def countNodes(root: TreeNode): Int = {
|
||||
if (root == null) return 0
|
||||
var leftNode = root.left
|
||||
var rightNode = root.right
|
||||
// 向左向右往下探
|
||||
var leftDepth = 0
|
||||
while (leftNode != null) {
|
||||
leftDepth += 1
|
||||
leftNode = leftNode.left
|
||||
}
|
||||
var rightDepth = 0
|
||||
while (rightNode != null) {
|
||||
rightDepth += 1
|
||||
rightNode = rightNode.right
|
||||
}
|
||||
// 如果相等就是一个满二叉树
|
||||
if (leftDepth == rightDepth) {
|
||||
return (2 << leftDepth) - 1
|
||||
}
|
||||
// 如果不相等就不是一个完全二叉树,继续向下递归
|
||||
countNodes(root.left) + countNodes(root.right) + 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 225. 用队列实现栈
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/implement-stack-using-queues/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/implement-stack-using-queues/)
|
||||
|
||||
使用队列实现栈的下列操作:
|
||||
|
||||
@ -816,7 +816,6 @@ class MyStack {
|
||||
}
|
||||
```
|
||||
Scala:
|
||||
|
||||
使用两个队列模拟栈:
|
||||
```scala
|
||||
import scala.collection.mutable
|
||||
@ -897,6 +896,86 @@ class MyStack() {
|
||||
def empty(): Boolean = {
|
||||
queue.isEmpty
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP
|
||||
> 双对列
|
||||
```php
|
||||
// SplQueue 类通过使用一个双向链表来提供队列的主要功能。(PHP 5 >= 5.3.0, PHP 7, PHP 8)
|
||||
// https://www.php.net/manual/zh/class.splqueue.php
|
||||
class MyStack {
|
||||
public $queueMain; // 保存数据
|
||||
public $queueTmp; // 辅助作用
|
||||
|
||||
function __construct() {
|
||||
$this->queueMain=new SplQueue();
|
||||
$this->queueTmp=new SplQueue();
|
||||
}
|
||||
|
||||
// queueMain: 1,2,3 <= add
|
||||
function push($x) {
|
||||
$this->queueMain->enqueue($x);
|
||||
}
|
||||
|
||||
function pop() {
|
||||
$qmSize = $this->queueMain->Count();
|
||||
$qmSize --;
|
||||
// queueMain: 3,2,1 => pop =>2,1 => add => 2,1 :queueTmp
|
||||
while($qmSize --){
|
||||
$this->queueTmp->enqueue($this->queueMain->dequeue());
|
||||
}
|
||||
// queueMain: 3
|
||||
$val = $this->queueMain->dequeue();
|
||||
// queueMain <= queueTmp
|
||||
$this->queueMain = $this->queueTmp;
|
||||
// 清空queueTmp,下次使用
|
||||
$this->queueTmp = new SplQueue();
|
||||
return $val;
|
||||
}
|
||||
|
||||
function top() {
|
||||
// 底层是双链表实现:从双链表的末尾查看节点
|
||||
return $this->queueMain->top();
|
||||
}
|
||||
|
||||
function empty() {
|
||||
return $this->queueMain->isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
> 单对列
|
||||
```php
|
||||
class MyStack {
|
||||
public $queue;
|
||||
|
||||
function __construct() {
|
||||
$this->queue=new SplQueue();
|
||||
}
|
||||
|
||||
function push($x) {
|
||||
$this->queue->enqueue($x);
|
||||
}
|
||||
|
||||
function pop() {
|
||||
$qmSize = $this->queue->Count();
|
||||
$qmSize --;
|
||||
//queue: 3,2,1 => pop =>2,1 => add => 2,1,3 :queue
|
||||
while($qmSize --){
|
||||
$this->queue->enqueue($this->queue->dequeue());
|
||||
}
|
||||
$val = $this->queue->dequeue();
|
||||
return $val;
|
||||
}
|
||||
|
||||
function top() {
|
||||
return $this->queue->top();
|
||||
}
|
||||
|
||||
function empty() {
|
||||
return $this->queue->isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 226.翻转二叉树
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/invert-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/invert-binary-tree/)
|
||||
|
||||
翻转一棵二叉树。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 232.用栈实现队列
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/implement-queue-using-stacks/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/implement-queue-using-stacks/)
|
||||
|
||||
使用栈实现队列的下列操作:
|
||||
|
||||
@ -495,6 +495,53 @@ void myQueueFree(MyQueue* obj) {
|
||||
obj->stackOutTop = 0;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
// SplStack 类通过使用一个双向链表来提供栈的主要功能。[PHP 5 >= 5.3.0, PHP 7, PHP 8]
|
||||
// https://www.php.net/manual/zh/class.splstack.php
|
||||
class MyQueue {
|
||||
// 双栈模拟队列:In栈存储数据;Out栈辅助处理
|
||||
private $stackIn;
|
||||
private $stackOut;
|
||||
|
||||
function __construct() {
|
||||
$this->stackIn = new SplStack();
|
||||
$this->stackOut = new SplStack();
|
||||
}
|
||||
|
||||
// In: 1 2 3 <= push
|
||||
function push($x) {
|
||||
$this->stackIn->push($x);
|
||||
}
|
||||
|
||||
function pop() {
|
||||
$this->peek();
|
||||
return $this->stackOut->pop();
|
||||
}
|
||||
|
||||
function peek() {
|
||||
if($this->stackOut->isEmpty()){
|
||||
$this->shift();
|
||||
}
|
||||
return $this->stackOut->top();
|
||||
}
|
||||
|
||||
function empty() {
|
||||
return $this->stackOut->isEmpty() && $this->stackIn->isEmpty();
|
||||
}
|
||||
|
||||
// 如果Out栈为空,把In栈数据压入Out栈
|
||||
// In: 1 2 3 => pop push => 1 2 3 :Out
|
||||
private function shift(){
|
||||
while(!$this->stackIn->isEmpty()){
|
||||
$this->stackOut->push($this->stackIn->pop());
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
class MyQueue() {
|
||||
@ -533,6 +580,7 @@ class MyQueue() {
|
||||
def empty(): Boolean = {
|
||||
stackIn.isEmpty && stackOut.isEmpty
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 234.回文链表
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/palindrome-linked-list/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/palindrome-linked-list/)
|
||||
|
||||
请判断一个链表是否为回文链表。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
# 235. 二叉搜索树的最近公共祖先
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/)
|
||||
|
||||
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
|
||||
|
||||
@ -381,7 +381,36 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||
// scala中每个关键字都有其返回值,于是可以不写return
|
||||
if (root.value > p.value && root.value > q.value) lowestCommonAncestor(root.left, p, q)
|
||||
else if (root.value < p.value && root.value < q.value) lowestCommonAncestor(root.right, p, q)
|
||||
else root
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||
var curNode = root // 因为root是不可变量,所以要赋值给curNode一个可变量
|
||||
while(curNode != null){
|
||||
if(curNode.value > p.value && curNode.value > q.value) curNode = curNode.left
|
||||
else if(curNode.value < p.value && curNode.value < q.value) curNode = curNode.right
|
||||
else return curNode
|
||||
}
|
||||
null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 236. 二叉树的最近公共祖先
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/)
|
||||
|
||||
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
|
||||
|
||||
@ -343,7 +343,25 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||
// 递归结束条件
|
||||
if (root == null || root == p || root == q) {
|
||||
return root
|
||||
}
|
||||
|
||||
var left = lowestCommonAncestor(root.left, p, q)
|
||||
var right = lowestCommonAncestor(root.right, p, q)
|
||||
|
||||
if (left != null && right != null) return root
|
||||
if (left == null) return right
|
||||
left
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 239. 滑动窗口最大值
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/sliding-window-maximum/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/sliding-window-maximum/)
|
||||
|
||||
给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
## 242.有效的字母异位词
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/valid-anagram/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/valid-anagram/)
|
||||
|
||||
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 257. 二叉树的所有路径
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-paths/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/binary-tree-paths/)
|
||||
|
||||
给定一个二叉树,返回所有从根节点到叶子节点的路径。
|
||||
|
||||
@ -702,5 +702,35 @@ func binaryTreePaths(_ root: TreeNode?) -> [String] {
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
|
||||
递归:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable.ListBuffer
|
||||
def binaryTreePaths(root: TreeNode): List[String] = {
|
||||
val res = ListBuffer[String]()
|
||||
def traversal(curNode: TreeNode, path: ListBuffer[Int]): Unit = {
|
||||
path.append(curNode.value)
|
||||
if (curNode.left == null && curNode.right == null) {
|
||||
res.append(path.mkString("->")) // mkString函数: 将数组的所有值按照指定字符串拼接
|
||||
return // 处理完可以直接return
|
||||
}
|
||||
|
||||
if (curNode.left != null) {
|
||||
traversal(curNode.left, path)
|
||||
path.remove(path.size - 1)
|
||||
}
|
||||
if (curNode.right != null) {
|
||||
traversal(curNode.right, path)
|
||||
path.remove(path.size - 1)
|
||||
}
|
||||
}
|
||||
traversal(root, ListBuffer[Int]())
|
||||
res.toList
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
## 279.完全平方数
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/perfect-squares/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/perfect-squares/)
|
||||
|
||||
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
# 283. 移动零
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/move-zeroes/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/move-zeroes/)
|
||||
|
||||
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
|
||||
|
||||
@ -133,6 +133,27 @@ var moveZeroes = function(nums) {
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
```typescript
|
||||
function moveZeroes(nums: number[]): void {
|
||||
const length: number = nums.length;
|
||||
let slowIndex: number = 0,
|
||||
fastIndex: number = 0;
|
||||
while (fastIndex < length) {
|
||||
if (nums[fastIndex] !== 0) {
|
||||
nums[slowIndex++] = nums[fastIndex];
|
||||
};
|
||||
fastIndex++;
|
||||
}
|
||||
while (slowIndex < length) {
|
||||
nums[slowIndex++] = 0;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 300.最长递增子序列
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/longest-increasing-subsequence/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/longest-increasing-subsequence/)
|
||||
|
||||
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
## 309.最佳买卖股票时机含冷冻期
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/)
|
||||
|
||||
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
## 322. 零钱兑换
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/coin-change/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/coin-change/)
|
||||
|
||||
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 332.重新安排行程
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/reconstruct-itinerary/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/reconstruct-itinerary/)
|
||||
|
||||
给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。
|
||||
|
||||
|
@ -7,7 +7,7 @@
|
||||
|
||||
## 337.打家劫舍 III
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/house-robber-iii/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/house-robber-iii/)
|
||||
|
||||
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
||||
|
||||
# 343. 整数拆分
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/integer-break/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/integer-break/)
|
||||
|
||||
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 344.反转字符串
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/reverse-string/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/reverse-string/)
|
||||
|
||||
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
|
||||
|
||||
@ -266,6 +266,38 @@ public class Solution
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
// 双指针
|
||||
// 一:
|
||||
function reverseString(&$s) {
|
||||
$left = 0;
|
||||
$right = count($s)-1;
|
||||
while($left<$right){
|
||||
$temp = $s[$left];
|
||||
$s[$left] = $s[$right];
|
||||
$s[$right] = $temp;
|
||||
$left++;
|
||||
$right--;
|
||||
}
|
||||
}
|
||||
|
||||
// 二:
|
||||
function reverseString(&$s) {
|
||||
$this->reverse($s,0,count($s)-1);
|
||||
}
|
||||
// 按指定位置交换元素
|
||||
function reverse(&$s, $start, $end) {
|
||||
for ($i = $start, $j = $end; $i < $j; $i++, $j--) {
|
||||
$tmp = $s[$i];
|
||||
$s[$i] = $s[$j];
|
||||
$s[$j] = $tmp;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
object Solution {
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
# 347.前 K 个高频元素
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/top-k-frequent-elements/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/top-k-frequent-elements/)
|
||||
|
||||
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
|
||||
|
||||
|
@ -12,7 +12,7 @@
|
||||
|
||||
## 349. 两个数组的交集
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/intersection-of-two-arrays/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/intersection-of-two-arrays/)
|
||||
|
||||
题意:给定两个数组,编写一个函数来计算它们的交集。
|
||||
|
||||
|
@ -9,7 +9,7 @@
|
||||
|
||||
# 376. 摆动序列
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/wiggle-subsequence/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/wiggle-subsequence/)
|
||||
|
||||
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
||||
|
||||
## 377. 组合总和 Ⅳ
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/combination-sum-iv/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/combination-sum-iv/)
|
||||
|
||||
难度:中等
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
# 383. 赎金信
|
||||
|
||||
[力扣题目链接](https://leetcode-cn.com/problems/ransom-note/)
|
||||
[力扣题目链接](https://leetcode.cn/problems/ransom-note/)
|
||||
|
||||
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user