Merge branch 'master' into 0020

This commit is contained in:
程序员Carl
2022-06-30 08:36:59 +08:00
committed by GitHub
179 changed files with 5147 additions and 416 deletions

View File

@ -7,7 +7,7 @@
## 1. 两数之和
[力扣题目链接](https://leetcode-cn.com/problems/two-sum/)
[力扣题目链接](https://leetcode.cn/problems/two-sum/)
给定一个整数数组 nums 和一个目标值 target请你在该数组中找出和为目标值的那 两个 整数并返回他们的数组下标。
@ -275,5 +275,48 @@ class Solution {
}
```
Scala:
```scala
object Solution {
// 导入包
import scala.collection.mutable
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
// key存储值value存储下标
val map = new mutable.HashMap[Int, Int]()
for (i <- nums.indices) {
val tmp = target - nums(i) // 计算差值
// 如果这个差值存在于map则说明找到了结果
if (map.contains(tmp)) {
return Array(map.get(tmp).get, i)
}
// 如果不包含把当前值与其下标放到map
map.put(nums(i), i)
}
// 如果没有找到直接返回一个空的数组return关键字可以省略
new Array[Int](2)
}
}
```
C#:
```csharp
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int ,int> dic= new Dictionary<int,int>();
for(int i=0;i<nums.Length;i++){
int imp= target-nums[i];
if(dic.ContainsKey(imp)&&dic[imp]!=i){
return new int[]{i, dic[imp]};
}
if(!dic.ContainsKey(nums[i])){
dic.Add(nums[i],i);
}
}
return new int[]{0, 0};
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -8,7 +8,7 @@
# 5.最长回文子串
[力扣题目链接](https://leetcode-cn.com/problems/longest-palindromic-substring/)
[力扣题目链接](https://leetcode.cn/problems/longest-palindromic-substring/)
给你一个字符串 s找到 s 中最长的回文子串。

View File

@ -10,7 +10,7 @@
# 第15题. 三数之和
[力扣题目链接](https://leetcode-cn.com/problems/3sum/)
[力扣题目链接](https://leetcode.cn/problems/3sum/)
给你一个包含 n 个整数的数组 nums判断 nums 中是否存在三个元素 abc 使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
@ -345,6 +345,76 @@ var threeSum = function(nums) {
return res
};
```
解法二nSum通用解法递归
```js
/**
* nsum通用解法支持2sum3sum4sum...等等
* 时间复杂度分析:
* 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
@ -616,6 +686,49 @@ public class Solution
}
}
```
Scala:
```scala
object Solution {
// 导包
import scala.collection.mutable.ListBuffer
import scala.util.control.Breaks.{break, breakable}
def threeSum(nums: Array[Int]): List[List[Int]] = {
// 定义结果集最后需要转换为List
val res = ListBuffer[List[Int]]()
val nums_tmp = nums.sorted // 对nums进行排序
for (i <- nums_tmp.indices) {
// 如果要排的第一个数字大于0直接返回结果
if (nums_tmp(i) > 0) {
return res.toList
}
// 如果i大于0并且和前一个数字重复则跳过本次循环相当于continue
breakable {
if (i > 0 && nums_tmp(i) == nums_tmp(i - 1)) {
break
} else {
var left = i + 1
var right = nums_tmp.length - 1
while (left < right) {
var sum = nums_tmp(i) + nums_tmp(left) + nums_tmp(right) // 求三数之和
if (sum < 0) left += 1
else if (sum > 0) right -= 1
else {
res += List(nums_tmp(i), nums_tmp(left), nums_tmp(right)) // 如果等于0 添加进结果集
// 为了避免重复对left和right进行移动
while (left < right && nums_tmp(left) == nums_tmp(left + 1)) left += 1
while (left < right && nums_tmp(right) == nums_tmp(right - 1)) right -= 1
left += 1
right -= 1
}
}
}
}
}
// 最终返回需要转换为Listreturn关键字可以省略
res.toList
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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 的字符串,返回所有它能表示的字母组合。

View File

@ -10,7 +10,7 @@
# 第18题. 四数之和
[力扣题目链接](https://leetcode-cn.com/problems/4sum/)
[力扣题目链接](https://leetcode.cn/problems/4sum/)
题意给定一个包含 n 个整数的数组 nums 和一个目标值 target判断 nums 中是否存在四个元素 abc 和 d 使得 a + b + c + d 的值与 target 相等找出所有满足条件且不重复的四元组。
@ -522,6 +522,49 @@ public class Solution
}
}
```
Scala:
```scala
object Solution {
// 导包
import scala.collection.mutable.ListBuffer
import scala.util.control.Breaks.{break, breakable}
def fourSum(nums: Array[Int], target: Int): List[List[Int]] = {
val res = ListBuffer[List[Int]]()
val nums_tmp = nums.sorted // 先排序
for (i <- nums_tmp.indices) {
breakable {
if (i > 0 && nums_tmp(i) == nums_tmp(i - 1)) {
break // 如果该值和上次的值相同跳过本次循环相当于continue
} else {
for (j <- i + 1 until nums_tmp.length) {
breakable {
if (j > i + 1 && nums_tmp(j) == nums_tmp(j - 1)) {
break // 同上
} else {
// 双指针
var (left, right) = (j + 1, nums_tmp.length - 1)
while (left < right) {
var sum = nums_tmp(i) + nums_tmp(j) + nums_tmp(left) + nums_tmp(right)
if (sum == target) {
// 满足要求,直接加入到集合里面去
res += List(nums_tmp(i), nums_tmp(j), nums_tmp(left), nums_tmp(right))
while (left < right && nums_tmp(left) == nums_tmp(left + 1)) left += 1
while (left < right && nums_tmp(right) == nums_tmp(right - 1)) right -= 1
left += 1
right -= 1
} else if (sum < target) left += 1
else right -= 1
}
}
}
}
}
}
}
// 最终返回的res要转换为Listreturn关键字可以省略
res.toList
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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 个结点,并且返回链表的头结点。
@ -290,5 +290,51 @@ func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
}
```
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 {
def removeNthFromEnd(head: ListNode, n: Int): ListNode = {
val dummy = new ListNode(-1, head) // 定义虚拟头节点
var fast = head // 快指针从头开始走
var slow = dummy // 慢指针从虚拟头开始头
// 因为参数 n 是不可变量,所以不能使用 while(n>0){n-=1}的方式
for (i <- 0 until n) {
fast = fast.next
}
// 快指针和满指针一起走直到fast走到null
while (fast != null) {
slow = slow.next
fast = fast.next
}
// 删除slow的下一个节点
slow.next = slow.next.next
// 返回虚拟头节点的下一个
dummy.next
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -10,7 +10,7 @@
# 20. 有效的括号
[力扣题目链接](https://leetcode-cn.com/problems/valid-parentheses/)
[力扣题目链接](https://leetcode.cn/problems/valid-parentheses/)
给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。
@ -401,6 +401,7 @@ bool isValid(char * s){
}
```
PHP:
```php
// https://www.php.net/manual/zh/class.splstack.php
@ -429,5 +430,29 @@ class Solution
}
```
Scala:
```scala
object Solution {
import scala.collection.mutable
def isValid(s: String): Boolean = {
if(s.length % 2 != 0) return false // 如果字符串长度是奇数直接返回false
val stack = mutable.Stack[Char]()
// 循环遍历字符串
for (i <- s.indices) {
val c = s(i)
if (c == '(' || c == '[' || c == '{') stack.push(c)
else if(stack.isEmpty) return false // 如果没有(、[、{则直接返回false
// 以下三种情况不满足则直接返回false
else if(c==')' && stack.pop() != '(') return false
else if(c==']' && stack.pop() != '[') return false
else if(c=='}' && stack.pop() != '{') return false
}
// 如果为空则正确匹配,否则还有余孽就不匹配
stack.isEmpty
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -7,7 +7,7 @@
## 24. 两两交换链表中的节点
[力扣题目链接](https://leetcode-cn.com/problems/swap-nodes-in-pairs/)
[力扣题目链接](https://leetcode.cn/problems/swap-nodes-in-pairs/)
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
@ -311,7 +311,29 @@ func swapPairs(_ head: ListNode?) -> ListNode? {
return dummyHead.next
}
```
Scala:
```scala
// 虚拟头节点
object Solution {
def swapPairs(head: ListNode): ListNode = {
var dummy = new ListNode(0, head) // 虚拟头节点
var pre = dummy
var cur = head
// 当pre的下一个和下下个都不为空才进行两两转换
while (pre.next != null && pre.next.next != null) {
var tmp: ListNode = cur.next.next // 缓存下一次要进行转换的第一个节点
pre.next = cur.next // 步骤一
cur.next.next = cur // 步骤二
cur.next = tmp // 步骤三
// 下面是准备下一轮的交换
pre = cur
cur = tmp
}
// 最终返回dummy虚拟头节点的下一个return可以省略
dummy.next
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -7,7 +7,7 @@
## 27. 移除元素
[力扣题目链接](https://leetcode-cn.com/problems/remove-element/)
[力扣题目链接](https://leetcode.cn/problems/remove-element/)
给你一个数组 nums 和一个值 val你需要 原地 移除所有数值等于 val 的元素并返回移除后数组的新长度。
@ -28,6 +28,8 @@
## 思路
[本题B站视频讲解](https://www.bilibili.com/video/BV12A4y1Z7LP)
有的同学可能说了,多余的元素,删掉不就得了。
**要知道数组的元素在内存地址中是连续的,不能单独删除数组中的某个元素,只能覆盖。**
@ -75,10 +77,20 @@ public:
双指针法(快慢指针法): **通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。**
定义快慢指针
* 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
* 慢指针:指向更新 新数组下标的位置
很多同学这道题目做的很懵,就是不理解 快慢指针究竟都是什么含义,所以一定要明确含义,后面的思路就更容易理解了。
删除过程如下:
![27.移除元素-双指针法](https://tva1.sinaimg.cn/large/008eGmZEly1gntrds6r59g30du09mnpd.gif)
很多同学不了解
**双指针法(快慢指针法)在数组和链表的操作中是非常常见的,很多考察数组、链表、字符串等操作的面试题,都使用双指针法。**
后续都会一一介绍到,本题代码如下:
@ -104,8 +116,6 @@ public:
* 时间复杂度O(n)
* 空间复杂度O(1)
旧文链接:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html)
```CPP
/**
* 相向双指针方法,基于元素顺序可以改变的题目描述改变了元素相对位置,确保了移动最少元素
@ -329,5 +339,34 @@ int removeElement(int* nums, int numsSize, int val){
}
```
Kotlin:
```kotlin
fun removeElement(nums: IntArray, `val`: Int): Int {
var slowIndex = 0 // 初始化慢指针
for (fastIndex in nums.indices) {
if (nums[fastIndex] != `val`) nums[slowIndex++] = nums[fastIndex] // 在慢指针所在位置存储未被删除的元素
}
return slowIndex
}
```
Scala:
```scala
object Solution {
def removeElement(nums: Array[Int], `val`: Int): Int = {
var slow = 0
for (fast <- 0 until nums.length) {
if (`val` != nums(fast)) {
nums(slow) = nums(fast)
slow += 1
}
}
slow
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -9,7 +9,7 @@
# 28. 实现 strStr()
[力扣题目链接](https://leetcode-cn.com/problems/implement-strstr/)
[力扣题目链接](https://leetcode.cn/problems/implement-strstr/)
实现 strStr() 函数。
@ -1166,5 +1166,80 @@ func strStr(_ haystack: String, _ needle: String) -> Int {
```
PHP
> 前缀表统一减一
```php
function strStr($haystack, $needle) {
if (strlen($needle) == 0) return 0;
$next= [];
$this->getNext($next,$needle);
$j = -1;
for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始
while($j >= 0 && $haystack[$i] != $needle[$j + 1]) {
$j = $next[$j];
}
if ($haystack[$i] == $needle[$j + 1]) {
$j++;
}
if ($j == (strlen($needle) - 1) ) {
return ($i - strlen($needle) + 1);
}
}
return -1;
}
function getNext(&$next, $s){
$j = -1;
$next[0] = $j;
for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始
while ($j >= 0 && $s[$i] != $s[$j + 1]) {
$j = $next[$j];
}
if ($s[$i] == $s[$j + 1]) {
$j++;
}
$next[$i] = $j;
}
}
```
> 前缀表统一不减一
```php
function strStr($haystack, $needle) {
if (strlen($needle) == 0) return 0;
$next= [];
$this->getNext($next,$needle);
$j = 0;
for ($i = 0;$i < strlen($haystack); $i++) { // 注意i就从0开始
while($j > 0 && $haystack[$i] != $needle[$j]) {
$j = $next[$j-1];
}
if ($haystack[$i] == $needle[$j]) {
$j++;
}
if ($j == strlen($needle)) {
return ($i - strlen($needle) + 1);
}
}
return -1;
}
function getNext(&$next, $s){
$j = 0;
$next[0] = $j;
for($i = 1; $i < strlen($s); $i++) { // 注意i从1开始
while ($j > 0 && $s[$i] != $s[$j]) {
$j = $next[$j-1];
}
if ($s[$i] == $s[$j]) {
$j++;
}
$next[$i] = $j;
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -9,7 +9,7 @@
# 31.下一个排列
[力扣题目链接](https://leetcode-cn.com/problems/next-permutation/)
[力扣题目链接](https://leetcode.cn/problems/next-permutation/)
实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

View File

@ -480,7 +480,52 @@ var searchRange = function(nums, target) {
return [-1, -1];
};
```
### Scala
```scala
object Solution {
def searchRange(nums: Array[Int], target: Int): Array[Int] = {
var left = getLeftBorder(nums, target)
var right = getRightBorder(nums, target)
if (left == -2 || right == -2) return Array(-1, -1)
if (right - left > 1) return Array(left + 1, right - 1)
Array(-1, -1)
}
// 寻找左边界
def getLeftBorder(nums: Array[Int], target: Int): Int = {
var leftBorder = -2
var left = 0
var right = nums.length - 1
while (left <= right) {
var mid = left + (right - left) / 2
if (nums(mid) >= target) {
right = mid - 1
leftBorder = right
} else {
left = mid + 1
}
}
leftBorder
}
// 寻找右边界
def getRightBorder(nums: Array[Int], target: Int): Int = {
var rightBorder = -2
var left = 0
var right = nums.length - 1
while (left <= right) {
var mid = left + (right - left) / 2
if (nums(mid) <= target) {
left = mid + 1
rightBorder = left
} else {
right = mid - 1
}
}
rightBorder
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -9,7 +9,7 @@
# 35.搜索插入位置
[力扣题目链接](https://leetcode-cn.com/problems/search-insert-position/)
[力扣题目链接](https://leetcode.cn/problems/search-insert-position/)
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
@ -73,8 +73,8 @@ public:
};
```
* 时间复杂度:$O(n)$
* 空间复杂度:$O(1)$
* 时间复杂度O(n)
* 空间复杂度O(1)
效率如下:
@ -135,14 +135,14 @@ public:
// 目标值在数组所有元素之前 [0, -1]
// 目标值等于数组中某一个元素 return middle;
// 目标值插入数组中的位置 [left, right]return right + 1
// 目标值在数组所有元素之后的情况 [left, right] return right + 1
// 目标值在数组所有元素之后的情况 [left, right] 因为是右闭区间,所以 return right + 1
return right + 1;
}
};
```
* 时间复杂度:$O(\log n)$
* 时间复杂度:$O(1)$
* 时间复杂度O(log n)
* 时间复杂度O(1)
效率如下:
![35_搜索插入位置2](https://img-blog.csdnimg.cn/2020121623272877.png)
@ -178,7 +178,7 @@ public:
// 目标值在数组所有元素之前 [0,0)
// 目标值等于数组中某一个元素 return middle
// 目标值插入数组中的位置 [left, right) return right 即可
// 目标值在数组所有元素之后的情况 [left, right)return right 即可
// 目标值在数组所有元素之后的情况 [left, right)因为是右开区间,所以 return right
return right;
}
};
@ -316,7 +316,26 @@ func searchInsert(_ nums: [Int], _ target: Int) -> Int {
return right + 1
}
```
### Scala
```scala
object Solution {
def searchInsert(nums: Array[Int], target: Int): Int = {
var left = 0
var right = nums.length - 1
while (left <= right) {
var mid = left + (right - left) / 2
if (target == nums(mid)) {
return mid
} else if (target > nums(mid)) {
left = mid + 1
} else {
right = mid - 1
}
}
right + 1
}
}
```
### PHP

View File

@ -9,7 +9,7 @@
# 37. 解数独
[力扣题目链接](https://leetcode-cn.com/problems/sudoku-solver/)
[力扣题目链接](https://leetcode.cn/problems/sudoku-solver/)
编写一个程序,通过填充空格来解决数独问题。

View File

@ -7,7 +7,7 @@
# 39. 组合总和
[力扣题目链接](https://leetcode-cn.com/problems/combination-sum/)
[力扣题目链接](https://leetcode.cn/problems/combination-sum/)
给定一个无重复元素的数组 candidates 和一个目标数 target 找出 candidates 中所有可以使数字和为 target 的组合。

View File

@ -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 的组合。

View File

@ -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:
一种更简便的双指针方法:

View File

@ -9,7 +9,7 @@
# 45.跳跃游戏II
[力扣题目链接](https://leetcode-cn.com/problems/jump-game-ii/)
[力扣题目链接](https://leetcode.cn/problems/jump-game-ii/)
给定一个非负整数数组,你最初位于数组的第一个位置。

View File

@ -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;

View File

@ -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++) {

View File

@ -7,7 +7,7 @@
# 第51题. N皇后
[力扣题目链接](https://leetcode-cn.com/problems/n-queens/)
[力扣题目链接](https://leetcode.cn/problems/n-queens/)
n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

View File

@ -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++代码

View File

@ -7,7 +7,7 @@
# 53. 最大子序和
[力扣题目链接](https://leetcode-cn.com/problems/maximum-subarray/)
[力扣题目链接](https://leetcode.cn/problems/maximum-subarray/)
给定一个整数数组 nums 找到一个具有最大和的连续子数组子数组最少包含一个元素返回其最大和。

View File

@ -6,7 +6,7 @@
## 53. 最大子序和
[力扣题目链接](https://leetcode-cn.com/problems/maximum-subarray/)
[力扣题目链接](https://leetcode.cn/problems/maximum-subarray/)
给定一个整数数组 nums 找到一个具有最大和的连续子数组子数组最少包含一个元素返回其最大和。
@ -186,6 +186,24 @@ const maxSubArray = nums => {
};
```
TypeScript
```typescript
function maxSubArray(nums: number[]): number {
/**
dp[i]以nums[i]结尾的最大和
*/
const dp: number[] = []
dp[0] = nums[0];
let resMax: number = 0;
for (let i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
resMax = Math.max(resMax, dp[i]);
}
return resMax;
};
```
-----------------------

View File

@ -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:

View File

@ -7,7 +7,7 @@
# 55. 跳跃游戏
[力扣题目链接](https://leetcode-cn.com/problems/jump-game/)
[力扣题目链接](https://leetcode.cn/problems/jump-game/)
给定一个非负整数数组,你最初位于数组的第一个位置。

View File

@ -7,7 +7,7 @@
# 56. 合并区间
[力扣题目链接](https://leetcode-cn.com/problems/merge-intervals/)
[力扣题目链接](https://leetcode.cn/problems/merge-intervals/)
给出一个区间的集合,请合并所有重叠的区间。
@ -96,7 +96,7 @@ public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> result;
if (intervals.size() == 0) return result;
// 排序的参数使用了lamda表达式
// 排序的参数使用了lambda表达式
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b){return a[0] < b[0];});
result.push_back(intervals[0]);

View File

@ -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 中间的位置就是(11)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为奇数的话需要单独给矩阵最中间的位置赋值
@ -130,57 +132,37 @@ Java
```Java
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0; // 控制循环次数
int[][] res = new int[n][n];
int start = 0; // 每次循环的开始点(start, start)
int count = 1; // 定义填充数字
int i, j;
// 循环次数
int loop = n / 2;
// 定义每次循环起始位置
int startX = 0;
int startY = 0;
// 定义偏移量
int offset = 1;
// 定义填充数字
int count = 1;
// 定义中间位置
int mid = n / 2;
while (loop > 0) {
int i = startX;
int j = startY;
while (loop++ < n / 2) { // 判断边界后loop从1开始
// 模拟上侧从左到右
for (; j<startY + n -offset; ++j) {
res[startX][j] = count++;
for (j = start; j < n - loop; j++) {
res[start][j] = count++;
}
// 模拟右侧从上到下
for (; i<startX + n -offset; ++i) {
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
// 模拟下侧从右到左
for (; j > startY; j--) {
for (; j >= loop; j--) {
res[i][j] = count++;
}
// 模拟左侧从下到上
for (; i > startX; i--) {
for (; i >= loop; i--) {
res[i][j] = count++;
}
loop--;
startX += 1;
startY += 1;
offset += 2;
start++;
}
if (n % 2 == 1) {
res[mid][mid] = count;
res[start][start] = count;
}
return res;
@ -564,6 +546,57 @@ int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
return ans;
}
```
Scala:
```scala
object Solution {
def generateMatrix(n: Int): Array[Array[Int]] = {
var res = Array.ofDim[Int](n, n) // 定义一个n*n的二维矩阵
var num = 1 // 标志当前到了哪个数字
var i = 0 // 横坐标
var j = 0 // 竖坐标
while (num <= n * n) {
// 向右当j不越界并且下一个要填的数字是空白时
while (j < n && res(i)(j) == 0) {
res(i)(j) = num // 当前坐标等于num
num += 1 // num++
j += 1 // 竖坐标+1
}
i += 1 // 下移一行
j -= 1 // 左移一列
// 剩下的都同上
// 向下
while (i < n && res(i)(j) == 0) {
res(i)(j) = num
num += 1
i += 1
}
i -= 1
j -= 1
// 向左
while (j >= 0 && res(i)(j) == 0) {
res(i)(j) = num
num += 1
j -= 1
}
i -= 1
j += 1
// 向上
while (i >= 0 && res(i)(j) == 0) {
res(i)(j) = num
num += 1
i -= 1
}
i += 1
j += 1
}
res
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -6,7 +6,7 @@
# 62.不同路径
[力扣题目链接](https://leetcode-cn.com/problems/unique-paths/)
[力扣题目链接](https://leetcode.cn/problems/unique-paths/)
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。

View File

@ -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” )。
@ -66,7 +66,7 @@ dp[i][j] 表示从0 0出发到(i, j) 有dp[i][j]条不同的路
所以代码为:
```
```cpp
if (obstacleGrid[i][j] == 0) { // 当(i, j)没有障碍的时候再推导dp[i][j]
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
@ -76,7 +76,7 @@ if (obstacleGrid[i][j] == 0) { // 当(i, j)没有障碍的时候再推导dp[i
在[62.不同路径](https://programmercarl.com/0062.不同路径.html)不同路径中我们给出如下的初始化:
```
```cpp
vector<vector<int>> dp(m, vector<int>(n, 0)); // 初始值为0
for (int i = 0; i < m; i++) dp[i][0] = 1;
for (int j = 0; j < n; j++) dp[0][j] = 1;
@ -138,6 +138,8 @@ public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) //如果在起点或终点出现了障碍直接返回0
return 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) dp[i][0] = 1;
for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) dp[0][j] = 1;

View File

@ -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 阶你才能到达楼顶。

View File

@ -11,7 +11,7 @@
## 70. 爬楼梯
[力扣题目链接](https://leetcode-cn.com/problems/climbing-stairs/)
[力扣题目链接](https://leetcode.cn/problems/climbing-stairs/)
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

View File

@ -6,7 +6,7 @@
## 72. 编辑距离
[力扣题目链接](https://leetcode-cn.com/problems/edit-distance/)
[力扣题目链接](https://leetcode.cn/problems/edit-distance/)
给你两个单词 word1 和 word2请你计算出将 word1 转换成 word2 所使用的最少操作数 。
@ -327,5 +327,42 @@ const minDistance = (word1, word2) => {
};
```
TypeScript
```typescript
function minDistance(word1: string, word2: string): number {
/**
dp[i][j]: word1前i个字符word2前j个字符最少操作数
dp[0][0]=0表示word1前0个字符为'', word2前0个字符为''
*/
const length1: number = word1.length,
length2: number = word2.length;
const dp: number[][] = new Array(length1 + 1).fill(0)
.map(_ => new Array(length2 + 1).fill(0));
for (let i = 0; i <= length1; i++) {
dp[i][0] = i;
}
for (let i = 0; i <= length2; i++) {
dp[0][i] = i;
}
for (let i = 1; i <= length1; i++) {
for (let j = 1; j <= length2; j++) {
if (word1[i - 1] === word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(
dp[i - 1][j],
dp[i][j - 1],
dp[i - 1][j - 1]
) + 1;
}
}
}
return dp[length1][length2];
};
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -9,7 +9,7 @@
# 第77题. 组合
[力扣题目链接](https://leetcode-cn.com/problems/combinations/ )
[力扣题目链接](https://leetcode.cn/problems/combinations/ )
给定两个整数 n 和 k返回 1 ... n 中所有可能的 k 个数的组合。

View File

@ -14,7 +14,7 @@
文中的回溯法是可以剪枝优化的本篇我们继续来看一下题目77. 组合。
链接https://leetcode-cn.com/problems/combinations/
链接https://leetcode.cn/problems/combinations/
**看本篇之前,需要先看[回溯算法:求组合问题!](https://programmercarl.com/0077.组合.html)**

View File

@ -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++) {

View File

@ -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>

View File

@ -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++) {

View File

@ -8,7 +8,7 @@
# 93.复原IP地址
[力扣题目链接](https://leetcode-cn.com/problems/restore-ip-addresses/)
[力扣题目链接](https://leetcode.cn/problems/restore-ip-addresses/)
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
@ -444,7 +444,7 @@ var restoreIpAddresses = function(s) {
return;
}
for(let j = i; j < s.length; j++) {
const str = s.substr(i, j - i + 1);
const str = s.slice(i, j + 1);
if(str.length > 3 || +str > 255) break;
if(str.length > 1 && str[0] === "0") break;
path.push(str);

View File

@ -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 为节点组成的二叉搜索树有多少种?

View File

@ -7,7 +7,7 @@
# 98.验证二叉搜索树
[力扣题目链接](https://leetcode-cn.com/problems/validate-binary-search-tree/)
[力扣题目链接](https://leetcode.cn/problems/validate-binary-search-tree/)
给定一个二叉树,判断其是否是一个有效的二叉搜索树。

View File

@ -8,7 +8,7 @@
# 100. 相同的树
[力扣题目链接](https://leetcode-cn.com/problems/same-tree/)
[力扣题目链接](https://leetcode.cn/problems/same-tree/)
给定两个二叉树,编写一个函数来检验它们是否相同。

View File

@ -7,7 +7,7 @@
# 101. 对称二叉树
[力扣题目链接](https://leetcode-cn.com/problems/symmetric-tree/)
[力扣题目链接](https://leetcode.cn/problems/symmetric-tree/)
给定一个二叉树,检查它是否是镜像对称的。
@ -725,5 +725,25 @@ func isSymmetric3(_ root: TreeNode?) -> Bool {
}
```
## Scala
递归:
```scala
object Solution {
def isSymmetric(root: TreeNode): Boolean = {
if (root == null) return true // 如果等于空直接返回true
def compare(left: TreeNode, right: TreeNode): Boolean = {
if (left == null && right == null) return true // 如果左右都为空则为true
if (left == null && right != null) return false // 如果左空右不空不对称返回false
if (left != null && right == null) return false // 如果左不空右空不对称返回false
// 如果左右的值相等,并且往下递归
left.value == right.value && compare(left.left, right.right) && compare(left.right, right.left)
}
// 分别比较左子树和右子树
compare(root.left, root.right)
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -26,7 +26,7 @@
# 102.二叉树的层序遍历
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/)
[力扣题目链接](https://leetcode.cn/problems/binary-tree-level-order-traversal/)
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
@ -82,6 +82,26 @@ public:
}
};
```
```CPP
# 递归法
class Solution {
public:
void order(TreeNode* cur, vector<vector<int>>& result, int depth)
{
if (cur == nullptr) return;
if (result.size() == depth) result.push_back(vector<int>());
result[depth].push_back(cur->val);
order(cur->left, result, depth + 1);
order(cur->right, result, depth + 1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
int depth = 0;
order(root, result, depth);
return result;
}
};
```
python3代码
@ -298,13 +318,68 @@ func levelOrder(_ root: TreeNode?) -> [[Int]] {
return result
}
```
Scala:
```scala
// 102.二叉树的层序遍历
object Solution {
import scala.collection.mutable
def levelOrder(root: TreeNode): List[List[Int]] = {
val res = mutable.ListBuffer[List[Int]]()
if (root == null) return res.toList
val queue = mutable.Queue[TreeNode]() // 声明一个队列
queue.enqueue(root) // 把根节点加入queue
while (!queue.isEmpty) {
val tmp = mutable.ListBuffer[Int]()
val len = queue.size // 求出len的长度
for (i <- 0 until len) { // 从0到当前队列长度的所有节点都加入到结果集
val curNode = queue.dequeue()
tmp.append(curNode.value)
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
res.append(tmp.toList)
}
res.toList
}
}
```
Rust:
```rust
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
let mut stack = Vec::new();
if root.is_none(){
return ans;
}
stack.push(root.unwrap());
while stack.is_empty()!= true{
let num = stack.len();
let mut level = Vec::new();
for _i in 0..num{
let tmp = stack.remove(0);
level.push(tmp.borrow_mut().val);
if tmp.borrow_mut().left.is_some(){
stack.push(tmp.borrow_mut().left.take().unwrap());
}
if tmp.borrow_mut().right.is_some(){
stack.push(tmp.borrow_mut().right.take().unwrap());
}
}
ans.push(level);
}
ans
}
```
**此时我们就掌握了二叉树的层序遍历了,那么如下九道力扣上的题目,只需要修改模板的两三行代码(不能再多了),便可打倒!**
# 107.二叉树的层次遍历 II
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/)
[力扣题目链接](https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/)
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
@ -528,9 +603,64 @@ func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
}
```
Scala:
```scala
// 107.二叉树的层次遍历II
object Solution {
import scala.collection.mutable
def levelOrderBottom(root: TreeNode): List[List[Int]] = {
val res = mutable.ListBuffer[List[Int]]()
if (root == null) return res.toList
val queue = mutable.Queue[TreeNode]()
queue.enqueue(root)
while (!queue.isEmpty) {
val tmp = mutable.ListBuffer[Int]()
val len = queue.size
for (i <- 0 until len) {
val curNode = queue.dequeue()
tmp.append(curNode.value)
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
res.append(tmp.toList)
}
// 最后翻转一下
res.reverse.toList
}
Rust:
```rust
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let mut ans = Vec::new();
let mut stack = Vec::new();
if root.is_none(){
return ans;
}
stack.push(root.unwrap());
while stack.is_empty()!= true{
let num = stack.len();
let mut level = Vec::new();
for _i in 0..num{
let tmp = stack.remove(0);
level.push(tmp.borrow_mut().val);
if tmp.borrow_mut().left.is_some(){
stack.push(tmp.borrow_mut().left.take().unwrap());
}
if tmp.borrow_mut().right.is_some(){
stack.push(tmp.borrow_mut().right.take().unwrap());
}
}
ans.push(level);
}
ans
}
```
# 199.二叉树的右视图
[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-right-side-view/)
[力扣题目链接](https://leetcode.cn/problems/binary-tree-right-side-view/)
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
@ -750,9 +880,34 @@ func rightSideView(_ root: TreeNode?) -> [Int] {
}
```
Scala:
```scala
// 199.二叉树的右视图
object Solution {
import scala.collection.mutable
def rightSideView(root: TreeNode): List[Int] = {
val res = mutable.ListBuffer[Int]()
if (root == null) return res.toList
val queue = mutable.Queue[TreeNode]()
queue.enqueue(root)
while (!queue.isEmpty) {
val len = queue.size
var curNode: TreeNode = null
for (i <- 0 until len) {
curNode = queue.dequeue()
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
res.append(curNode.value) // 把最后一个节点的值加入解集
}
res.toList // 最后需要把res转换为Listreturn关键字可以省略
}
}
```
# 637.二叉树的层平均值
[力扣题目链接](https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/)
[力扣题目链接](https://leetcode.cn/problems/average-of-levels-in-binary-tree/)
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
@ -981,10 +1136,34 @@ func averageOfLevels(_ root: TreeNode?) -> [Double] {
return result
}
```
Scala:
```scala
// 637.二叉树的层平均值
object Solution {
import scala.collection.mutable
def averageOfLevels(root: TreeNode): Array[Double] = {
val res = mutable.ArrayBuffer[Double]()
val queue = mutable.Queue[TreeNode]()
queue.enqueue(root)
while (!queue.isEmpty) {
var sum = 0.0
var len = queue.size
for (i <- 0 until len) {
var curNode = queue.dequeue()
sum += curNode.value // 累加该层的值
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
res.append(sum / len) // 平均值即为sum/len
}
res.toArray // 最后需要转换为Arrayreturn关键字可以省略
}
}
```
# 429.N叉树的层序遍历
[力扣题目链接](https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/)
[力扣题目链接](https://leetcode.cn/problems/n-ary-tree-level-order-traversal/)
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
@ -1225,9 +1404,37 @@ func levelOrder(_ root: Node?) -> [[Int]] {
}
```
Scala:
```scala
// 429.N叉树的层序遍历
object Solution {
import scala.collection.mutable
def levelOrder(root: Node): List[List[Int]] = {
val res = mutable.ListBuffer[List[Int]]()
if (root == null) return res.toList
val queue = mutable.Queue[Node]()
queue.enqueue(root) // 根节点入队
while (!queue.isEmpty) {
val tmp = mutable.ListBuffer[Int]() // 存储每层节点
val len = queue.size
for (i <- 0 until len) {
val curNode = queue.dequeue()
tmp.append(curNode.value) // 将该节点的值加入tmp
// 循环遍历该节点的子节点,加入队列
for (child <- curNode.children) {
queue.enqueue(child)
}
}
res.append(tmp.toList) // 将该层的节点放到结果集
}
res.toList
}
}
```
# 515.在每个树行中找最大值
[力扣题目链接](https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/)
[力扣题目链接](https://leetcode.cn/problems/find-largest-value-in-each-tree-row/)
您需要在二叉树的每一行中找到最大的值。
@ -1433,9 +1640,35 @@ func largestValues(_ root: TreeNode?) -> [Int] {
}
```
Scala:
```scala
// 515.在每个树行中找最大值
object Solution {
import scala.collection.mutable
def largestValues(root: TreeNode): List[Int] = {
val res = mutable.ListBuffer[Int]()
if (root == null) return res.toList
val queue = mutable.Queue[TreeNode]()
queue.enqueue(root)
while (!queue.isEmpty) {
var max = Int.MinValue // 初始化max为系统最小值
val len = queue.size
for (i <- 0 until len) {
val curNode = queue.dequeue()
max = math.max(max, curNode.value) // 对比求解最大值
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
res.append(max) // 将最大值放入结果集
}
res.toList
}
}
```
# 116.填充每个节点的下一个右侧节点指针
[力扣题目链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/)
[力扣题目链接](https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/)
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
@ -1692,9 +1925,38 @@ func connect(_ root: Node?) -> Node? {
}
```
Scala:
```scala
// 116.填充每个节点的下一个右侧节点指针
object Solution {
import scala.collection.mutable
def connect(root: Node): Node = {
if (root == null) return root
val queue = mutable.Queue[Node]()
queue.enqueue(root)
while (!queue.isEmpty) {
val len = queue.size
val tmp = mutable.ListBuffer[Node]()
for (i <- 0 until len) {
val curNode = queue.dequeue()
tmp.append(curNode)
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
// 处理next指针
for (i <- 0 until tmp.size - 1) {
tmp(i).next = tmp(i + 1)
}
tmp(tmp.size-1).next = null
}
root
}
}
```
# 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/)
思路:
@ -1943,9 +2205,38 @@ func connect(_ root: Node?) -> Node? {
}
```
Scala:
```scala
// 117.填充每个节点的下一个右侧节点指针II
object Solution {
import scala.collection.mutable
def connect(root: Node): Node = {
if (root == null) return root
val queue = mutable.Queue[Node]()
queue.enqueue(root)
while (!queue.isEmpty) {
val len = queue.size
val tmp = mutable.ListBuffer[Node]()
for (i <- 0 until len) {
val curNode = queue.dequeue()
tmp.append(curNode)
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
}
// 处理next指针
for (i <- 0 until tmp.size - 1) {
tmp(i).next = tmp(i + 1)
}
tmp(tmp.size-1).next = null
}
root
}
}
```
# 104.二叉树的最大深度
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
[力扣题目链接](https://leetcode.cn/problems/maximum-depth-of-binary-tree/)
给定一个二叉树,找出其最大深度。
@ -2160,9 +2451,33 @@ func maxDepth(_ root: TreeNode?) -> Int {
}
```
Scala:
```scala
// 104.二叉树的最大深度
object Solution {
import scala.collection.mutable
def maxDepth(root: TreeNode): Int = {
if (root == null) return 0
val queue = mutable.Queue[TreeNode]()
queue.enqueue(root)
var depth = 0
while (!queue.isEmpty) {
val len = queue.length
depth += 1
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
}
}
```
# 111.二叉树的最小深度
[力扣题目链接](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/)
[力扣题目链接](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)
相对于 104.二叉树的最大深度 ,本题还也可以使用层序遍历的方式来解决,思路是一样的。
@ -2379,6 +2694,30 @@ func minDepth(_ root: TreeNode?) -> Int {
}
```
Scala:
```scala
// 111.二叉树的最小深度
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
}
}
```
# 总结

View File

@ -12,7 +12,7 @@
# 104.二叉树的最大深度
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/)
[力扣题目链接](https://leetcode.cn/problems/maximum-depth-of-binary-tree/)
给定一个二叉树,找出其最大深度。
@ -192,11 +192,38 @@ public:
};
```
rust:
```rust
impl Solution {
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if root.is_none(){
return 0;
}
let mut max_depth: i32 = 0;
let mut stack = vec![root.unwrap()];
while !stack.is_empty() {
let num = stack.len();
for _i in 0..num{
let top = stack.remove(0);
if top.borrow_mut().left.is_some(){
stack.push(top.borrow_mut().left.take().unwrap());
}
if top.borrow_mut().right.is_some(){
stack.push(top.borrow_mut().right.take().unwrap());
}
}
max_depth+=1;
}
max_depth
}
```
那么我们可以顺便解决一下n叉树的最大深度问题
# 559.n叉树的最大深度
[力扣题目链接](https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/)
[力扣题目链接](https://leetcode.cn/problems/maximum-depth-of-n-ary-tree/)
给定一个 n 叉树,找到其最大深度。
@ -468,7 +495,7 @@ class solution:
## go
### 104.二叉树的最大深度
```go
/**
* definition for a binary tree node.
@ -521,6 +548,8 @@ func maxdepth(root *treenode) int {
## javascript
### 104.二叉树的最大深度
```javascript
var maxdepth = function(root) {
if (root === null) return 0;
@ -568,6 +597,8 @@ var maxDepth = function(root) {
};
```
### 559.n叉树的最大深度
N叉树的最大深度 递归写法
```js
var maxDepth = function(root) {
@ -600,9 +631,9 @@ var maxDepth = function(root) {
};
```
## TypeScript
## TypeScript
> 二叉树的最大深度
### 104.二叉树的最大深度
```typescript
// 后续遍历(自下而上)
@ -645,7 +676,7 @@ function maxDepth(root: TreeNode | null): number {
};
```
> N叉树的最大深度
### 559.n叉树的最大深度
```typescript
// 后续遍历(自下而上)
@ -675,6 +706,8 @@ function maxDepth(root: TreeNode | null): number {
## C
### 104.二叉树的最大深度
二叉树最大深度递归
```c
int maxDepth(struct TreeNode* root){
@ -731,7 +764,8 @@ int maxDepth(struct TreeNode* root){
## Swift
>二叉树最大深度
### 104.二叉树最大深度
```swift
// 递归 - 后序
func maxDepth1(_ root: TreeNode?) -> Int {
@ -770,7 +804,8 @@ func maxDepth(_ root: TreeNode?) -> Int {
}
```
>N叉树最大深度
### 559.n叉树最大深度
```swift
// 递归
func maxDepth(_ root: Node?) -> Int {
@ -806,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>

View File

@ -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 // 返回rootreturn关键字可以省略
}
}
```
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>

View File

@ -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/)
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

View File

@ -9,7 +9,7 @@
# 110.平衡二叉树
[力扣题目链接](https://leetcode-cn.com/problems/balanced-binary-tree/)
[力扣题目链接](https://leetcode.cn/problems/balanced-binary-tree/)
给定一个二叉树,判断它是否是高度平衡的二叉树。
@ -208,7 +208,7 @@ int getHeight(TreeNode* node) {
```CPP
class Solution {
public:
// 返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
// 返回以该节点为根节点的二叉树的高度,如果不是平衡二叉树了则返回-1
int getHeight(TreeNode* node) {
if (node == NULL) {
return 0;

View File

@ -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,5 +488,110 @@ 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 {
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
return Solution::bfs(root)
}
// 递归
pub fn dfs(node: Option<Rc<RefCell<TreeNode>>>) -> i32{
if node.is_none(){
return 0;
}
let parent = node.unwrap();
let left_child = parent.borrow_mut().left.take();
let right_child = parent.borrow_mut().right.take();
if left_child.is_none() && right_child.is_none(){
return 1;
}
let mut min_depth = i32::MAX;
if left_child.is_some(){
let left_depth = Solution::dfs(left_child);
if left_depth <= min_depth{
min_depth = left_depth
}
}
if right_child.is_some(){
let right_depth = Solution::dfs(right_child);
if right_depth <= min_depth{
min_depth = right_depth
}
}
min_depth + 1
}
// 迭代
pub fn bfs(node: Option<Rc<RefCell<TreeNode>>>) -> i32{
let mut min_depth = 0;
if node.is_none(){
return min_depth
}
let mut stack = vec![node.unwrap()];
while !stack.is_empty(){
min_depth += 1;
let num = stack.len();
for _i in 0..num{
let top = stack.remove(0);
let left_child = top.borrow_mut().left.take();
let right_child = top.borrow_mut().right.take();
if left_child.is_none() && right_child.is_none(){
return min_depth;
}
if left_child.is_some(){
stack.push(left_child.unwrap());
}
if right_child.is_some(){
stack.push(right_child.unwrap());
}
}
}
min_depth
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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即可返回falsereturn关键字可以省略
}
}
```
### 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>

View File

@ -6,7 +6,7 @@
## 115.不同的子序列
[力扣题目链接](https://leetcode-cn.com/problems/distinct-subsequences/)
[力扣题目链接](https://leetcode.cn/problems/distinct-subsequences/)
给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。
@ -267,6 +267,36 @@ const numDistinct = (s, t) => {
};
```
TypeScript
```typescript
function numDistinct(s: string, t: string): number {
/**
dp[i][j]: s前i个字符t前j个字符s子序列中t出现的个数
dp[0][0]=1, 表示s前0个字符为''t前0个字符为''
*/
const sLen: number = s.length,
tLen: number = t.length;
const dp: number[][] = new Array(sLen + 1).fill(0)
.map(_ => new Array(tLen + 1).fill(0));
for (let m = 0; m < sLen; m++) {
dp[m][0] = 1;
}
for (let i = 1; i <= sLen; i++) {
for (let j = 1; j <= tLen; j++) {
if (s[i - 1] === t[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[sLen][tLen];
};
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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/)
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

View File

@ -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 天的价格。
@ -426,6 +426,46 @@ var maxProfit = function(prices) {
};
```
TypeScript
> 贪心法
```typescript
function maxProfit(prices: number[]): number {
if (prices.length === 0) return 0;
let buy: number = prices[0];
let profitMax: number = 0;
for (let i = 1, length = prices.length; i < length; i++) {
profitMax = Math.max(profitMax, prices[i] - buy);
buy = Math.min(prices[i], buy);
}
return profitMax;
};
```
> 动态规划
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 第i天持有股票的最大现金
dp[i][1]: 第i天不持有股票的最大现金
*/
const length = prices.length;
if (length === 0) return 0;
const dp: number[][] = [];
dp[0] = [-prices[0], 0];
for (let i = 1; i < length; i++) {
dp[i] = [];
dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]);
}
return dp[length - 1][1];
};
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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 天的价格。

View File

@ -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 天的价格。
@ -295,6 +295,42 @@ const maxProfit = (prices) => {
}
```
TypeScript
> 动态规划
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 第i天持有股票
dp[i][1]: 第i天不持有股票
*/
const length: number = prices.length;
if (length === 0) return 0;
const dp: number[][] = new Array(length).fill(0).map(_ => []);
dp[0] = [-prices[0], 0];
for (let i = 1; i < length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return dp[length - 1][1];
};
```
> 贪心法
```typescript
function maxProfit(prices: number[]): number {
let resProfit: number = 0;
for (let i = 1, length = prices.length; i < length; i++) {
if (prices[i] > prices[i - 1]) {
resProfit += prices[i] - prices[i - 1];
}
}
return resProfit;
};
```
-----------------------

View File

@ -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 天的价格。
@ -352,6 +352,36 @@ const maxProfit = prices => {
};
```
TypeScript
> 版本一
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 无操作;
dp[i][1]: 第一次买入;
dp[i][2]: 第一次卖出;
dp[i][3]: 第二次买入;
dp[i][4]: 第二次卖出;
*/
const length: number = prices.length;
if (length === 0) return 0;
const dp: number[][] = new Array(length).fill(0)
.map(_ => new Array(5).fill(0));
dp[0][1] = -prices[0];
dp[0][3] = -prices[0];
for (let i = 1; i < length; i++) {
dp[i][0] = dp[i - 1][0];
dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
}
return Math.max(dp[length - 1][2], dp[length - 1][4]);
};
```
Go:
> 版本一:

View File

@ -7,7 +7,7 @@
# 127. 单词接龙
[力扣题目链接](https://leetcode-cn.com/problems/word-ladder/)
[力扣题目链接](https://leetcode.cn/problems/word-ladder/)
字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列:
* 序列中第一个单词是 beginWord 。

View File

@ -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/)
# 思路

View File

@ -9,7 +9,7 @@
# 131.分割回文串
[力扣题目链接](https://leetcode-cn.com/problems/palindrome-partitioning/)
[力扣题目链接](https://leetcode.cn/problems/palindrome-partitioning/)
给定一个字符串 s将 s 分割成一些子串,使每个子串都是回文串。
@ -442,7 +442,7 @@ var partition = function(s) {
}
for(let j = i; j < len; j++) {
if(!isPalindrome(s, i, j)) continue;
path.push(s.substr(i, j - i + 1));
path.push(s.slice(i, j + 1));
backtracking(j + 1);
path.pop();
}

View File

@ -8,7 +8,7 @@
# 132. 分割回文串 II
[力扣题目链接](https://leetcode-cn.com/problems/palindrome-partitioning-ii/)
[力扣题目链接](https://leetcode.cn/problems/palindrome-partitioning-ii/)
给你一个字符串 s请你将 s 分割成一些子串,使每个子串都是回文。

View File

@ -7,7 +7,7 @@
# 134. 加油站
[力扣题目链接](https://leetcode-cn.com/problems/gas-station/)
[力扣题目链接](https://leetcode.cn/problems/gas-station/)
在一条环路上有 N 个加油站其中第 i 个加油站有汽油 gas[i] 升。

View File

@ -7,7 +7,7 @@
# 135. 分发糖果
[力扣题目链接](https://leetcode-cn.com/problems/candy/)
[力扣题目链接](https://leetcode.cn/problems/candy/)
老师想给孩子们分发糖果,有 N 个孩子站成了一条直线老师会根据每个孩子的表现预先给他们评分。

View File

@ -8,7 +8,7 @@
## 139.单词拆分
[力扣题目链接](https://leetcode-cn.com/problems/word-break/)
[力扣题目链接](https://leetcode.cn/problems/word-break/)
给定一个非空字符串 s 和一个包含非空单词的列表 wordDict判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

View File

@ -11,7 +11,7 @@
## 142.环形链表II
[力扣题目链接](https://leetcode-cn.com/problems/linked-list-cycle-ii/)
[力扣题目链接](https://leetcode.cn/problems/linked-list-cycle-ii/)
题意:
给定一个链表返回链表开始入环的第一个节点。 如果链表无环则返回 null。
@ -370,7 +370,31 @@ ListNode *detectCycle(ListNode *head) {
}
```
Scala:
```scala
object Solution {
def detectCycle(head: ListNode): ListNode = {
var fast = head // 快指针
var slow = head // 慢指针
while (fast != null && fast.next != null) {
fast = fast.next.next // 快指针一次走两步
slow = slow.next // 慢指针一次走一步
// 如果相遇fast快指针回到头
if (fast == slow) {
fast = head
// 两个指针一步一步的走,第一次相遇的节点必是入环节点
while (fast != slow) {
fast = fast.next
slow = slow.next
}
return fast
}
}
// 如果fast指向空值必然无环返回null
null
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -11,7 +11,7 @@
# 150. 逆波兰表达式求值
[力扣题目链接](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/)
[力扣题目链接](https://leetcode.cn/problems/evaluate-reverse-polish-notation/)
根据 逆波兰表示法,求表达式的值。
@ -136,19 +136,19 @@ java:
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList();
for (int i = 0; i < tokens.length; ++i) {
if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题不能使用==判断字符串是否相等
for (String s : tokens) {
if ("+".equals(s)) { // leetcode 内置jdk的问题不能使用==判断字符串是否相等
stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理
} else if ("-".equals(tokens[i])) {
} else if ("-".equals(s)) {
stack.push(-stack.pop() + stack.pop());
} else if ("*".equals(tokens[i])) {
} else if ("*".equals(s)) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(tokens[i])) {
} else if ("/".equals(s)) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
stack.push(Integer.valueOf(tokens[i]));
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
@ -325,6 +325,33 @@ func evalRPN(_ tokens: [String]) -> Int {
return stack.last!
}
```
Scala:
```scala
object Solution {
import scala.collection.mutable
def evalRPN(tokens: Array[String]): Int = {
val stack = mutable.Stack[Int]() // 定义栈
// 抽取运算操作需要传递x,y和一个函数
def operator(x: Int, y: Int, f: (Int, Int) => Int): Int = f(x, y)
for (token <- tokens) {
// 模式匹配,匹配不同的操作符做什么样的运算
token match {
// 最后一个参数 _+_代表x+y遵循Scala的函数至简原则以下运算同理
case "+" => stack.push(operator(stack.pop(), stack.pop(), _ + _))
case "-" => stack.push(operator(stack.pop(), stack.pop(), -_ + _))
case "*" => stack.push(operator(stack.pop(), stack.pop(), _ * _))
case "/" => {
var pop1 = stack.pop()
var pop2 = stack.pop()
stack.push(operator(pop2, pop1, _ / _))
}
case _ => stack.push(token.toInt) // 不是运算符就入栈
}
}
// 最后返回栈顶不需要加return关键字
stack.pop()
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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说明不是第一个单词需要在单词前添加空格。
@ -758,9 +758,112 @@ func reverseWord(_ s: inout [Character]) {
}
```
Scala:
```scala
object Solution {
def reverseWords(s: String): String = {
var sb = removeSpace(s) // 移除多余的空格
reverseString(sb, 0, sb.length - 1) // 翻转字符串
reverseEachWord(sb)
sb.mkString
}
// 移除多余的空格
def removeSpace(s: String): Array[Char] = {
var start = 0
var end = s.length - 1
// 移除字符串前面的空格
while (start < s.length && s(start) == ' ') start += 1
// 移除字符串后面的空格
while (end >= 0 && s(end) == ' ') end -= 1
var sb = "" // String
// 当start小于等于end的时候执行添加操作
while (start <= end) {
var c = s(start)
// 当前字符不等于空sb的最后一个字符不等于空的时候添加到sb
if (c != ' ' || sb(sb.length - 1) != ' ') {
sb ++= c.toString
}
start += 1 // 指针向右移动
}
sb.toArray
}
// 翻转字符串
def reverseString(s: Array[Char], start: Int, end: Int): Unit = {
var (left, right) = (start, end)
while (left < right) {
var tmp = s(left)
s(left) = s(right)
s(right) = tmp
left += 1
right -= 1
}
}
// 翻转每个单词
def reverseEachWord(s: Array[Char]): Unit = {
var i = 0
while (i < s.length) {
var j = i + 1
// 向后迭代寻找每个单词的坐标
while (j < s.length && s(j) != ' ') j += 1
reverseString(s, i, j - 1) // 翻转每个单词
i = j + 1 // i往后更新
}
}
}
```
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 ;
}
```
-----------------------

View File

@ -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 天的价格。
@ -409,5 +409,27 @@ var maxProfit = function(k, prices) {
};
```
TypeScript
```typescript
function maxProfit(k: number, prices: number[]): number {
const length: number = prices.length;
if (length === 0) return 0;
const dp: number[][] = new Array(length).fill(0)
.map(_ => new Array(k * 2 + 1).fill(0));
for (let i = 1; i <= k; i++) {
dp[0][i * 2 - 1] = -prices[0];
}
for (let i = 1; i < length; i++) {
for (let j = 1; j < 2 * k + 1; j++) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + Math.pow(-1, j) * prices[i]);
}
}
return dp[length - 1][2 * k];
};
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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--;
}
}
```
-----------------------

View File

@ -6,7 +6,7 @@
## 198.打家劫舍
[力扣题目链接](https://leetcode-cn.com/problems/house-robber/)
[力扣题目链接](https://leetcode.cn/problems/house-robber/)
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。

View File

@ -10,7 +10,7 @@
# 第202题. 快乐数
[力扣题目链接](https://leetcode-cn.com/problems/happy-number/)
[力扣题目链接](https://leetcode.cn/problems/happy-number/)
编写一个算法来判断一个数 n 是不是快乐数。
@ -385,5 +385,62 @@ bool isHappy(int n){
return bHappy;
}
```
Scala:
```scala
object Solution {
// 引入mutable
import scala.collection.mutable
def isHappy(n: Int): Boolean = {
// 存放每次计算后的结果
val set: mutable.HashSet[Int] = new mutable.HashSet[Int]()
var tmp = n // 因为形参是不可变量,所以需要找到一个临时变量
// 开始进入循环
while (true) {
val sum = getSum(tmp) // 获取这个数每个值的平方和
if (sum == 1) return true // 如果最终等于 1则返回true
// 如果set里面已经有这个值了说明进入无限循环可以返回false否则添加这个值到set
if (set.contains(sum)) return false
else set.add(sum)
tmp = sum
}
// 最终需要返回值直接返回个false
false
}
def getSum(n: Int): Int = {
var sum = 0
var tmp = n
while (tmp != 0) {
sum += (tmp % 10) * (tmp % 10)
tmp = tmp / 10
}
sum
}
```
C#
```csharp
public class Solution {
private int getSum(int n) {
int sum = 0;
//每位数的换算
while (n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
public bool IsHappy(int n) {
HashSet <int> set = new HashSet<int>();
while(n != 1 && !set.Contains(n)) { //判断避免循环
set.Add(n);
n = getSum(n);
}
return n == 1;
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -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。
![203_链表删除元素1](https://img-blog.csdnimg.cn/20210316095351161.png)
@ -266,6 +268,27 @@ public ListNode removeElements(ListNode head, int val) {
}
return head;
}
/**
* 不添加虚拟节点and pre Node方式
* 时间复杂度 O(n)
* 空间复杂度 O(1)
* @param head
* @param val
* @return
*/
public ListNode removeElements(ListNode head, int val) {
while(head!=null && head.val==val){
head = head.next;
}
ListNode curr = head;
while(curr!=null){
while(curr.next!=null && curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
}
```
Python
@ -478,6 +501,36 @@ impl Solution {
}
}
```
Scala:
```scala
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def removeElements(head: ListNode, `val`: Int): ListNode = {
if (head == null) return head
var dummy = new ListNode(-1, head) // 定义虚拟头节点
var cur = head // cur 表示当前节点
var pre = dummy // pre 表示cur前一个节点
while (cur != null) {
if (cur.x == `val`) {
// 相等就删除那么cur的前一个节点pre执行cur的下一个
pre.next = cur.next
} else {
// 不相等pre就等于当前cur节点
pre = cur
}
// 向下迭代
cur = cur.next
}
// 最终返回dummy的下一个就是链表的头
dummy.next
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -7,7 +7,7 @@
# 205. 同构字符串
[力扣题目链接](https://leetcode-cn.com/problems/isomorphic-strings/)
[力扣题目链接](https://leetcode.cn/problems/isomorphic-strings/)
给定两个字符串 s  t判断它们是否是同构的。

View File

@ -9,7 +9,7 @@
# 206.反转链表
[力扣题目链接](https://leetcode-cn.com/problems/reverse-linked-list/)
[力扣题目链接](https://leetcode.cn/problems/reverse-linked-list/)
题意:反转一个单链表。
@ -497,5 +497,58 @@ struct ListNode* reverseList(struct ListNode* head){
}
```
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 {
def reverseList(head: ListNode): ListNode = {
var pre: ListNode = null
var cur = head
while (cur != null) {
var tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
}
pre
}
}
```
递归法:
```scala
object Solution {
def reverseList(head: ListNode): ListNode = {
reverse(null, head)
}
def reverse(pre: ListNode, cur: ListNode): ListNode = {
if (cur == null) {
return pre // 如果当前cur为空则返回pre
}
val tmp: ListNode = cur.next
cur.next = pre
reverse(cur, tmp) // 此时cur成为前一个节点tmp是当前节点
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -5,9 +5,9 @@
<p align="center"><strong><a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
## 209.长度最小的子数组
# 209.长度最小的子数组
[力扣题目链接](https://leetcode-cn.com/problems/minimum-size-subarray-sum/)
[力扣题目链接](https://leetcode.cn/problems/minimum-size-subarray-sum/)
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
@ -17,6 +17,9 @@
输出2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
# 思路
为了易于大家理解,我特意录制了[拿下滑动窗口! | LeetCode 209 长度最小的子数组](https://www.bilibili.com/video/BV1tZ4y1q7XE)
## 暴力解法
@ -47,8 +50,8 @@ public:
}
};
```
时间复杂度O(n^2)
空间复杂度O(1)
* 时间复杂度O(n^2)
* 空间复杂度O(1)
## 滑动窗口
@ -56,6 +59,20 @@ public:
所谓滑动窗口,**就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果**。
在暴力解法中是一个for循环滑动窗口的起始位置一个for循环为滑动窗口的终止位置用两个for循环 完成了一个不断搜索区间的过程。
那么滑动窗口如何用一个for循环来完成这个操作呢。
首先要思考 如果用一个for循环那么应该表示 滑动窗口的起始位置,还是终止位置。
如果只用一个for循环来表示 滑动窗口的起始位置,那么如何遍历剩下的终止位置?
此时难免再次陷入 暴力解法的怪圈。
所以 只用一个for循环那么这个循环的索引一定是表示 滑动窗口的终止位置。
那么问题来了, 滑动窗口的起始位置如何移动呢?
这里还是以题目中的示例来举例s=7 数组是 231243来看一下查找的过程
![209.长度最小的子数组](https://code-thinking.cdn.bcebos.com/gifs/209.%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84.gif)
@ -74,7 +91,7 @@ public:
窗口的起始位置如何移动如果当前窗口的值大于s了窗口就要向前移动了也就是该缩小了
窗口的结束位置如何移动:窗口的结束位置就是遍历数组的指针,窗口的起始位置设置为数组的起始位置就可以了
窗口的结束位置如何移动:窗口的结束位置就是遍历数组的指针,也就是for循环里的索引
解题的关键在于 窗口的起始位置如何移动,如图所示:
@ -107,8 +124,8 @@ public:
};
```
时间复杂度O(n)
空间复杂度O(1)
* 时间复杂度O(n)
* 空间复杂度O(1)
**一些录友会疑惑为什么时间复杂度是O(n)**
@ -116,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/)

View File

@ -6,7 +6,7 @@
## 213.打家劫舍II
[力扣题目链接](https://leetcode-cn.com/problems/house-robber-ii/)
[力扣题目链接](https://leetcode.cn/problems/house-robber-ii/)
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。

View File

@ -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 的正整数,并且每种组合中不存在重复的数字。
@ -360,39 +360,30 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
## javaScript
```js
// 等差数列
var maxV = k => k * (9 + 10 - k) / 2;
var minV = k => k * (1 + k) / 2;
/**
* @param {number} k
* @param {number} n
* @return {number[][]}
*/
var combinationSum3 = function(k, n) {
if (k > 9 || k < 1) return [];
// if (n > maxV(k) || n < minV(k)) return [];
// if (n === maxV(k)) return [Array.from({length: k}).map((v, i) => 9 - i)];
// if (n === minV(k)) return [Array.from({length: k}).map((v, i) => i + 1)];
const res = [], path = [];
backtracking(k, n, 1, 0);
return res;
function backtracking(k, n, i, sum){
const len = path.length;
if (len > k || sum > n) return;
if (maxV(k - len) < n - sum) return;
if (minV(k - len) > n - sum) return;
if(len === k && sum == n) {
res.push(Array.from(path));
const backtrack = (start) => {
const l = path.length;
if (l === k) {
const sum = path.reduce((a, b) => a + b);
if (sum === n) {
res.push([...path]);
}
return;
}
const min = Math.min(n - sum, 9 + len - k + 1);
for(let a = i; a <= min; a++) {
path.push(a);
sum += a;
backtracking(k, n, a + 1, sum);
for (let i = start; i <= 9 - (k - l) + 1; i++) {
path.push(i);
backtrack(i + 1);
path.pop();
sum -= a;
}
}
let res = [], path = [];
backtrack(1);
return res;
};
```

View File

@ -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>

View File

@ -10,7 +10,7 @@
# 225. 用队列实现栈
[力扣题目链接](https://leetcode-cn.com/problems/implement-stack-using-queues/)
[力扣题目链接](https://leetcode.cn/problems/implement-stack-using-queues/)
使用队列实现栈的下列操作:
@ -815,6 +815,168 @@ class MyStack {
}
}
```
Scala:
使用两个队列模拟栈:
```scala
import scala.collection.mutable
class MyStack() {
val queue1 = new mutable.Queue[Int]()
val queue2 = new mutable.Queue[Int]()
def push(x: Int) {
queue1.enqueue(x)
}
def pop(): Int = {
var size = queue1.size
// 将queue1中的每个元素都移动到queue2
for (i <- 0 until size - 1) {
queue2.enqueue(queue1.dequeue())
}
var res = queue1.dequeue()
// 再将queue2中的每个元素都移动到queue1
while (!queue2.isEmpty) {
queue1.enqueue(queue2.dequeue())
}
res
}
def top(): Int = {
var size = queue1.size
for (i <- 0 until size - 1) {
queue2.enqueue(queue1.dequeue())
}
var res = queue1.dequeue()
while (!queue2.isEmpty) {
queue1.enqueue(queue2.dequeue())
}
// 最终还需要把res送进queue1
queue1.enqueue(res)
res
}
def empty(): Boolean = {
queue1.isEmpty
}
}
```
使用一个队列模拟:
```scala
import scala.collection.mutable
class MyStack() {
val queue = new mutable.Queue[Int]()
def push(x: Int) {
queue.enqueue(x)
}
def pop(): Int = {
var size = queue.size
for (i <- 0 until size - 1) {
queue.enqueue(queue.head) // 把头添到队列最后
queue.dequeue() // 再出队
}
queue.dequeue()
}
def top(): Int = {
var size = queue.size
var res = 0
for (i <- 0 until size) {
queue.enqueue(queue.head) // 把头添到队列最后
res = queue.dequeue() // 再出队
}
res
}
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();
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -7,7 +7,7 @@
# 226.翻转二叉树
[力扣题目链接](https://leetcode-cn.com/problems/invert-binary-tree/)
[力扣题目链接](https://leetcode.cn/problems/invert-binary-tree/)
翻转一棵二叉树。
@ -368,9 +368,7 @@ func invertTree(root *TreeNode) *TreeNode {
if root ==nil{
return nil
}
temp:=root.Left
root.Left=root.Right
root.Right=temp
root.Left,root.Right=root.Right,root.Left//交换
invertTree(root.Left)
invertTree(root.Right)
@ -820,5 +818,53 @@ func invertTree(_ root: TreeNode?) -> TreeNode? {
}
```
### Scala
深度优先遍历(前序遍历):
```scala
object Solution {
def invertTree(root: TreeNode): TreeNode = {
if (root == null) return root
// 递归
def process(node: TreeNode): Unit = {
if (node == null) return
// 翻转节点
val curNode = node.left
node.left = node.right
node.right = curNode
process(node.left)
process(node.right)
}
process(root)
root
}
}
```
广度优先遍历(层序遍历):
```scala
object Solution {
import scala.collection.mutable
def invertTree(root: TreeNode): TreeNode = {
if (root == null) return root
val queue = mutable.Queue[TreeNode]()
queue.enqueue(root)
while (!queue.isEmpty) {
val len = queue.size
for (i <- 0 until len) {
var curNode = queue.dequeue()
if (curNode.left != null) queue.enqueue(curNode.left)
if (curNode.right != null) queue.enqueue(curNode.right)
// 翻转
var tmpNode = curNode.left
curNode.left = curNode.right
curNode.right = tmpNode
}
}
root
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -9,7 +9,7 @@
# 232.用栈实现队列
[力扣题目链接](https://leetcode-cn.com/problems/implement-queue-using-stacks/)
[力扣题目链接](https://leetcode.cn/problems/implement-queue-using-stacks/)
使用栈实现队列的下列操作:
@ -496,5 +496,92 @@ void myQueueFree(MyQueue* obj) {
}
```
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() {
import scala.collection.mutable
val stackIn = mutable.Stack[Int]() // 负责出栈
val stackOut = mutable.Stack[Int]() // 负责入栈
// 添加元素
def push(x: Int) {
stackIn.push(x)
}
// 复用代码如果stackOut为空就把stackIn的所有元素都压入StackOut
def dumpStackIn(): Unit = {
if (!stackOut.isEmpty) return
while (!stackIn.isEmpty) {
stackOut.push(stackIn.pop())
}
}
// 弹出元素
def pop(): Int = {
dumpStackIn()
stackOut.pop()
}
// 获取队头
def peek(): Int = {
dumpStackIn()
val res: Int = stackOut.pop()
stackOut.push(res)
res
}
// 判断是否为空
def empty(): Boolean = {
stackIn.isEmpty && stackOut.isEmpty
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -7,7 +7,7 @@
# 234.回文链表
[力扣题目链接](https://leetcode-cn.com/problems/palindrome-linked-list/)
[力扣题目链接](https://leetcode.cn/problems/palindrome-linked-list/)
请判断一个链表是否为回文链表。

View File

@ -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/)
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

View File

@ -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/)
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

View File

@ -10,7 +10,7 @@
# 239. 滑动窗口最大值
[力扣题目链接](https://leetcode-cn.com/problems/sliding-window-maximum/)
[力扣题目链接](https://leetcode.cn/problems/sliding-window-maximum/)
给定一个数组 nums有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
@ -630,6 +630,53 @@ func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
return result
}
```
Scala:
```scala
import scala.collection.mutable.ArrayBuffer
object Solution {
def maxSlidingWindow(nums: Array[Int], k: Int): Array[Int] = {
var len = nums.length - k + 1 // 滑动窗口长度
var res: Array[Int] = new Array[Int](len) // 声明存储结果的数组
var index = 0 // 结果数组指针
val queue: MyQueue = new MyQueue // 自定义队列
// 将前k个添加到queue
for (i <- 0 until k) {
queue.add(nums(i))
}
res(index) = queue.peek // 第一个滑动窗口的最大值
index += 1
for (i <- k until nums.length) {
queue.poll(nums(i - k)) // 首先移除第i-k个元素
queue.add(nums(i)) // 添加当前数字到队列
res(index) = queue.peek() // 赋值
index+=1
}
// 最终返回resreturn关键字可以省略
res
}
}
class MyQueue {
var queue = ArrayBuffer[Int]()
// 移除元素,如果传递进来的跟队头相等,那么移除
def poll(value: Int): Unit = {
if (!queue.isEmpty && queue.head == value) {
queue.remove(0)
}
}
// 添加元素,当队尾大于当前元素就删除
def add(value: Int): Unit = {
while (!queue.isEmpty && value > queue.last) {
queue.remove(queue.length - 1)
}
queue.append(value)
}
def peek(): Int = queue.head
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -9,7 +9,7 @@
## 242.有效的字母异位词
[力扣题目链接](https://leetcode-cn.com/problems/valid-anagram/)
[力扣题目链接](https://leetcode.cn/problems/valid-anagram/)
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
@ -307,6 +307,52 @@ impl Solution {
}
}
```
Scala:
```scala
object Solution {
def isAnagram(s: String, t: String): Boolean = {
// 如果两个字符串的长度不等直接返回false
if (s.length != t.length) return false
val record = new Array[Int](26) // 记录每个单词出现了多少次
// 遍历字符串对于s字符串单词对应的记录+=1t字符串对应的记录-=1
for (i <- 0 until s.length) {
record(s(i) - 97) += 1
record(t(i) - 97) -= 1
}
// 如果不等于则直接返回false
for (i <- 0 until 26) {
if (record(i) != 0) {
return false
}
}
// 如果前面不返回false说明匹配成功返回truereturn可以省略
true
}
}
```
C#
```csharp
public bool IsAnagram(string s, string t) {
int sl=s.Length,tl=t.Length;
if(sl!=tl) return false;
int[] a = new int[26];
for(int i = 0; i < sl; i++){
a[s[i] - 'a']++;
a[t[i] - 'a']--;
}
foreach (int i in a)
{
if (i != 0)
return false;
}
return true;
}
```
## 相关题目
* 383.赎金信

View File

@ -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>

View File

@ -7,7 +7,7 @@
## 279.完全平方数
[力扣题目链接](https://leetcode-cn.com/problems/perfect-squares/)
[力扣题目链接](https://leetcode.cn/problems/perfect-squares/)
给定正整数 n找到若干个完全平方数比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

View File

@ -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>

View File

@ -6,7 +6,7 @@
## 300.最长递增子序列
[力扣题目链接](https://leetcode-cn.com/problems/longest-increasing-subsequence/)
[力扣题目链接](https://leetcode.cn/problems/longest-increasing-subsequence/)
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
@ -237,6 +237,27 @@ const lengthOfLIS = (nums) => {
};
```
TypeScript
```typescript
function lengthOfLIS(nums: number[]): number {
/**
dp[i]: 前i个元素中以nums[i]结尾,最长子序列的长度
*/
const dp: number[] = new Array(nums.length).fill(1);
let resMax: number = 0;
for (let i = 0, length = nums.length; i < length; i++) {
for (let j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
resMax = Math.max(resMax, dp[i]);
}
return resMax;
};
```

View File

@ -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 天的股票价格 。
@ -325,6 +325,66 @@ const maxProfit = (prices) => {
};
```
TypeScript
> 版本一,与本文思路一致
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 持股状态;
dp[i][1]: 无股状态,当天为非冷冻期;
dp[i][2]: 无股状态,当天卖出;
dp[i][3]: 无股状态,当天为冷冻期;
*/
const length: number = prices.length;
const dp: number[][] = new Array(length).fill(0).map(_ => []);
dp[0][0] = -prices[0];
dp[0][1] = dp[0][2] = dp[0][3] = 0;
for (let i = 1; i < length; i++) {
dp[i][0] = Math.max(
dp[i - 1][0],
Math.max(dp[i - 1][1], dp[i - 1][3]) - prices[i]
);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][3]);
dp[i][2] = dp[i - 1][0] + prices[i];
dp[i][3] = dp[i - 1][2];
}
const lastEl: number[] = dp[length - 1];
return Math.max(lastEl[1], lastEl[2], lastEl[3]);
};
```
> 版本二,状态定义略有不同,可以帮助理解
```typescript
function maxProfit(prices: number[]): number {
/**
dp[i][0]: 持股状态,当天买入;
dp[i][1]: 持股状态,当天未买入;
dp[i][2]: 无股状态,当天卖出;
dp[i][3]: 无股状态,当天未卖出;
买入有冷冻期限制,其实就是状态[0]只能由前一天的状态[3]得到;
如果卖出有冷冻期限制,其实就是[2]由[1]得到。
*/
const length: number = prices.length;
const dp: number[][] = new Array(length).fill(0).map(_ => []);
dp[0][0] = -prices[0];
dp[0][1] = -Infinity;
dp[0][2] = dp[0][3] = 0;
for (let i = 1; i < length; i++) {
dp[i][0] = dp[i - 1][3] - prices[i];
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0]);
dp[i][2] = Math.max(dp[i - 1][0], dp[i - 1][1]) + prices[i];
dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2]);
}
return Math.max(dp[length - 1][2], dp[length - 1][3]);
};
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -7,7 +7,7 @@
## 322. 零钱兑换
[力扣题目链接](https://leetcode-cn.com/problems/coin-change/)
[力扣题目链接](https://leetcode.cn/problems/coin-change/)
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额返回 -1。

View File

@ -9,7 +9,7 @@
# 332.重新安排行程
[力扣题目链接](https://leetcode-cn.com/problems/reconstruct-itinerary/)
[力扣题目链接](https://leetcode.cn/problems/reconstruct-itinerary/)
给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从 JFK肯尼迪国际机场出发的先生所以该行程必须从 JFK 开始。

View File

@ -7,7 +7,7 @@
## 337.打家劫舍 III
[力扣题目链接](https://leetcode-cn.com/problems/house-robber-iii/)
[力扣题目链接](https://leetcode.cn/problems/house-robber-iii/)
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
@ -429,7 +429,50 @@ const rob = root => {
};
```
### TypeScript
> 记忆化后序遍历
```typescript
const memory: Map<TreeNode, number> = new Map();
function rob(root: TreeNode | null): number {
if (root === null) return 0;
if (memory.has(root)) return memory.get(root);
// 不取当前节点
const res1: number = rob(root.left) + rob(root.right);
// 取当前节点
let res2: number = root.val;
if (root.left !== null) res2 += rob(root.left.left) + rob(root.left.right);
if (root.right !== null) res2 += rob(root.right.left) + rob(root.right.right);
const res: number = Math.max(res1, res2);
memory.set(root, res);
return res;
};
```
> 状态标记化后序遍历
```typescript
function rob(root: TreeNode | null): number {
return Math.max(...robNode(root));
};
// [0]-不偷当前节点能获得的最大金额; [1]-偷~~
type MaxValueArr = [number, number];
function robNode(node: TreeNode | null): MaxValueArr {
if (node === null) return [0, 0];
const leftArr: MaxValueArr = robNode(node.left);
const rightArr: MaxValueArr = robNode(node.right);
// 不偷
const val1: number = Math.max(leftArr[0], leftArr[1]) +
Math.max(rightArr[0], rightArr[1]);
// 偷
const val2: number = leftArr[0] + rightArr[0] + node.val;
return [val1, val2];
}
```
### Go
```go
// 打家劫舍Ⅲ 动态规划
// 时间复杂度O(n) 空间复杂度O(logn)

View File

@ -6,7 +6,7 @@
# 343. 整数拆分
[力扣题目链接](https://leetcode-cn.com/problems/integer-break/)
[力扣题目链接](https://leetcode.cn/problems/integer-break/)
给定一个正整数 n将其拆分为至少两个正整数的和并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

View File

@ -10,7 +10,7 @@
# 344.反转字符串
[力扣题目链接](https://leetcode-cn.com/problems/reverse-string/)
[力扣题目链接](https://leetcode.cn/problems/reverse-string/)
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
@ -267,5 +267,51 @@ 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 {
def reverseString(s: Array[Char]): Unit = {
var (left, right) = (0, s.length - 1)
while (left < right) {
var tmp = s(left)
s(left) = s(right)
s(right) = tmp
left += 1
right -= 1
}
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -11,7 +11,7 @@
# 347.前 K 个高频元素
[力扣题目链接](https://leetcode-cn.com/problems/top-k-frequent-elements/)
[力扣题目链接](https://leetcode.cn/problems/top-k-frequent-elements/)
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
@ -374,7 +374,49 @@ function topKFrequent(nums: number[], k: number): number[] {
};
```
Scala:
解法一: 优先级队列
```scala
object Solution {
import scala.collection.mutable
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
val map = mutable.HashMap[Int, Int]()
// 将所有元素都放入Map
for (num <- nums) {
map.put(num, map.getOrElse(num, 0) + 1)
}
// 声明一个优先级队列,在函数柯里化那块需要指明排序方式
var queue = mutable.PriorityQueue[(Int, Int)]()(Ordering.fromLessThan((x, y) => x._2 > y._2))
// 将map里面的元素送入优先级队列
for (elem <- map) {
queue.enqueue(elem)
if(queue.size > k){
queue.dequeue // 如果队列元素大于k个出队
}
}
// 最终只需要key的Array形式就可以了return关键字可以省略
queue.map(_._1).toArray
}
}
```
解法二: 相当于一个wordCount程序
```scala
object Solution {
def topKFrequent(nums: Array[Int], k: Int): Array[Int] = {
// 首先将数据变为(x,1)然后按照x分组再使用map进行转换(x,sum)变换为Array
// 再使用sort针对sum进行排序最后take前k个再把数据变为x,y,z这种格式
nums.map((_, 1)).groupBy(_._1)
.map {
case (x, arr) => (x, arr.map(_._2).sum)
}
.toArray
.sortWith(_._2 > _._2)
.take(k)
.map(_._1)
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -12,7 +12,7 @@
## 349. 两个数组的交集
[力扣题目链接](https://leetcode-cn.com/problems/intersection-of-two-arrays/)
[力扣题目链接](https://leetcode.cn/problems/intersection-of-two-arrays/)
题意:给定两个数组,编写一个函数来计算它们的交集。
@ -313,6 +313,71 @@ int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* re
}
```
Scala:
正常解法:
```scala
object Solution {
def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
// 导入mutable
import scala.collection.mutable
// 临时Set用于记录数组1出现的每个元素
val tmpSet: mutable.HashSet[Int] = new mutable.HashSet[Int]()
// 结果Set存储最终结果
val resSet: mutable.HashSet[Int] = new mutable.HashSet[Int]()
// 遍历nums1把每个元素添加到tmpSet
nums1.foreach(tmpSet.add(_))
// 遍历nums2如果在tmpSet存在就添加到resSet
nums2.foreach(elem => {
if (tmpSet.contains(elem)) {
resSet.add(elem)
}
})
// 将结果转换为Array返回return可以省略
resSet.toArray
}
}
```
骚操作1:
```scala
object Solution {
def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
// 先转为Set然后取交集最后转换为Array
(nums1.toSet).intersect(nums2.toSet).toArray
}
}
```
骚操作2:
```scala
object Solution {
def intersection(nums1: Array[Int], nums2: Array[Int]): Array[Int] = {
// distinct去重然后取交集
(nums1.distinct).intersect(nums2.distinct)
}
}
```
C#:
```csharp
public int[] Intersection(int[] nums1, int[] nums2) {
if(nums1==null||nums1.Length==0||nums2==null||nums1.Length==0)
return new int[0]; //注意数组条件
HashSet<int> one = Insert(nums1);
HashSet<int> two = Insert(nums2);
one.IntersectWith(two);
return one.ToArray();
}
public HashSet<int> Insert(int[] nums){
HashSet<int> one = new HashSet<int>();
foreach(int num in nums){
one.Add(num);
}
return one;
}
```
## 相关题目
* 350.两个数组的交集 II

View File

@ -9,7 +9,7 @@
# 376. 摆动序列
[力扣题目链接](https://leetcode-cn.com/problems/wiggle-subsequence/)
[力扣题目链接](https://leetcode.cn/problems/wiggle-subsequence/)
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。

View File

@ -8,7 +8,7 @@
## 377. 组合总和 Ⅳ
[力扣题目链接](https://leetcode-cn.com/problems/combination-sum-iv/)
[力扣题目链接](https://leetcode.cn/problems/combination-sum-iv/)
难度:中等

View File

@ -10,7 +10,7 @@
# 383. 赎金信
[力扣题目链接](https://leetcode-cn.com/problems/ransom-note/)
[力扣题目链接](https://leetcode.cn/problems/ransom-note/)
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
@ -363,5 +363,88 @@ impl Solution {
}
```
Scala:
版本一: 使用数组作为哈希表
```scala
object Solution {
def canConstruct(ransomNote: String, magazine: String): Boolean = {
// 如果magazine的长度小于ransomNote的长度必然是false
if (magazine.length < ransomNote.length) {
return false
}
// 定义一个数组存储magazine字符出现的次数
val map: Array[Int] = new Array[Int](26)
// 遍历magazine字符串对应的字符+=1
for (i <- magazine.indices) {
map(magazine(i) - 'a') += 1
}
// 遍历ransomNote
for (i <- ransomNote.indices) {
if (map(ransomNote(i) - 'a') > 0)
map(ransomNote(i) - 'a') -= 1
else return false
}
// 如果上面没有返回false直接返回true关键字return可以省略
true
}
}
```
```scala
object Solution {
import scala.collection.mutable
def canConstruct(ransomNote: String, magazine: String): Boolean = {
// 如果magazine的长度小于ransomNote的长度必然是false
if (magazine.length < ransomNote.length) {
return false
}
// 定义mapkey是字符value是字符出现的次数
val map = new mutable.HashMap[Char, Int]()
// 遍历magazine把所有的字符都记录到map里面
for (i <- magazine.indices) {
val tmpChar = magazine(i)
// 如果map包含该字符那么对应的value++,否则添加该字符
if (map.contains(tmpChar)) {
map.put(tmpChar, map.get(tmpChar).get + 1)
} else {
map.put(tmpChar, 1)
}
}
// 遍历ransomNote
for (i <- ransomNote.indices) {
val tmpChar = ransomNote(i)
// 如果map包含并且该字符的value大于0则匹配成功map对应的--否则直接返回false
if (map.contains(tmpChar) && map.get(tmpChar).get > 0) {
map.put(tmpChar, map.get(tmpChar).get - 1)
} else {
return false
}
}
// 如果上面没有返回false直接返回true关键字return可以省略
true
}
}
```
C#
```csharp
public bool CanConstruct(string ransomNote, string magazine) {
if(ransomNote.Length > magazine.Length) return false;
int[] letters = new int[26];
foreach(char c in magazine){
letters[c-'a']++;
}
foreach(char c in ransomNote){
letters[c-'a']--;
if(letters[c-'a']<0){
return false;
}
}
return true;
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

Some files were not shown because too many files have changed in this diff Show More