diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 9571a773..fb3c1d45 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -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 dic= new Dictionary(); + for(int i=0;i diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index eaebb5ab..d53acf63 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -8,7 +8,7 @@ # 5.最长回文子串 -[力扣题目链接](https://leetcode-cn.com/problems/longest-palindromic-substring/) +[力扣题目链接](https://leetcode.cn/problems/longest-palindromic-substring/) 给你一个字符串 s,找到 s 中最长的回文子串。 diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index cc184c87..4f1d711a 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -10,7 +10,7 @@ # 第15题. 三数之和 -[力扣题目链接](https://leetcode-cn.com/problems/3sum/) +[力扣题目链接](https://leetcode.cn/problems/3sum/) 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。 @@ -345,6 +345,76 @@ var threeSum = function(nums) { return res }; ``` + +解法二:nSum通用解法。递归 + +```js +/** + * nsum通用解法,支持2sum,3sum,4sum...等等 + * 时间复杂度分析: + * 1. n = 2时,时间复杂度O(NlogN),排序所消耗的时间。、 + * 2. n > 2时,时间复杂度为O(N^n-1),即N的n-1次方,至少是2次方,此时可省略排序所消耗的时间。举例:3sum为O(n^2),4sum为O(n^3) + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function (nums) { + // nsum通用解法核心方法 + function nSumTarget(nums, n, start, target) { + // 前提:nums要先排序好 + let res = []; + if (n === 2) { + res = towSumTarget(nums, start, target); + } else { + for (let i = start; i < nums.length; i++) { + // 递归求(n - 1)sum + let subRes = nSumTarget( + nums, + n - 1, + i + 1, + target - nums[i] + ); + for (let j = 0; j < subRes.length; j++) { + res.push([nums[i], ...subRes[j]]); + } + // 跳过相同元素 + while (nums[i] === nums[i + 1]) i++; + } + } + return res; + } + + function towSumTarget(nums, start, target) { + // 前提:nums要先排序好 + let res = []; + let len = nums.length; + let left = start; + let right = len - 1; + while (left < right) { + let sum = nums[left] + nums[right]; + if (sum < target) { + while (nums[left] === nums[left + 1]) left++; + left++; + } else if (sum > target) { + while (nums[right] === nums[right - 1]) right--; + right--; + } else { + // 相等 + res.push([nums[left], nums[right]]); + // 跳过相同元素 + while (nums[left] === nums[left + 1]) left++; + while (nums[right] === nums[right - 1]) right--; + left++; + right--; + } + } + return res; + } + nums.sort((a, b) => a - b); + // n = 3,此时求3sum之和 + return nSumTarget(nums, 3, 0, 0); +}; +``` + TypeScript: ```typescript @@ -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 + } + } + } + } + } + // 最终返回需要转换为List,return关键字可以省略 + res.toList + } +} +``` -----------------------
diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 94136565..2b5cb978 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -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 的字符串,返回所有它能表示的字母组合。 diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index ee70cb69..2146a114 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -10,7 +10,7 @@ # 第18题. 四数之和 -[力扣题目链接](https://leetcode-cn.com/problems/4sum/) +[力扣题目链接](https://leetcode.cn/problems/4sum/) 题意:给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 @@ -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要转换为List,return关键字可以省略 + res.toList + } +} +``` -----------------------
diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index b3030a81..3499ab9d 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -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 + } +} +``` -----------------------
diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 5e468549..c3ff9d53 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -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 + } +} +``` + -----------------------
diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index ce75e0d7..e636bfff 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -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 + } +} +``` -----------------------
diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 3a93ac88..03c58b43 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -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 + } +} +``` + -----------------------
diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index d67e5f70..a95a52f8 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -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; + } +} +``` -----------------------
diff --git a/problems/0031.下一个排列.md b/problems/0031.下一个排列.md index 2219e24d..bce8adef 100644 --- a/problems/0031.下一个排列.md +++ b/problems/0031.下一个排列.md @@ -9,7 +9,7 @@ # 31.下一个排列 -[力扣题目链接](https://leetcode-cn.com/problems/next-permutation/) +[力扣题目链接](https://leetcode.cn/problems/next-permutation/) 实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index dfd90b82..260462c2 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -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 + } +} +``` -----------------------
diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 8a8f9706..ed7c49b4 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -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 diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index c1ac15af..b074b98f 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -9,7 +9,7 @@ # 37. 解数独 -[力扣题目链接](https://leetcode-cn.com/problems/sudoku-solver/) +[力扣题目链接](https://leetcode.cn/problems/sudoku-solver/) 编写一个程序,通过填充空格来解决数独问题。 diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index e10a827f..fef9b676 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -7,7 +7,7 @@ # 39. 组合总和 -[力扣题目链接](https://leetcode-cn.com/problems/combination-sum/) +[力扣题目链接](https://leetcode.cn/problems/combination-sum/) 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 34ac64e6..ee4371cd 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -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 的组合。 diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index b232ce22..4832423d 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -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: 一种更简便的双指针方法: diff --git a/problems/0045.跳跃游戏II.md b/problems/0045.跳跃游戏II.md index 4e3ab24a..9e61fbb8 100644 --- a/problems/0045.跳跃游戏II.md +++ b/problems/0045.跳跃游戏II.md @@ -9,7 +9,7 @@ # 45.跳跃游戏II -[力扣题目链接](https://leetcode-cn.com/problems/jump-game-ii/) +[力扣题目链接](https://leetcode.cn/problems/jump-game-ii/) 给定一个非负整数数组,你最初位于数组的第一个位置。 diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 836c3646..9f93564c 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -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; diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index cce25cd9..f5f9e440 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -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++) { diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index c03e48c2..798902ae 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -7,7 +7,7 @@ # 第51题. N皇后 -[力扣题目链接](https://leetcode-cn.com/problems/n-queens/) +[力扣题目链接](https://leetcode.cn/problems/n-queens/) n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 diff --git a/problems/0052.N皇后II.md b/problems/0052.N皇后II.md index 67e439ca..97d31a25 100644 --- a/problems/0052.N皇后II.md +++ b/problems/0052.N皇后II.md @@ -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++代码 diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 73cac244..cbc91481 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -7,7 +7,7 @@ # 53. 最大子序和 -[力扣题目链接](https://leetcode-cn.com/problems/maximum-subarray/) +[力扣题目链接](https://leetcode.cn/problems/maximum-subarray/) 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md index 4c883cb6..345abc27 100644 --- a/problems/0053.最大子序和(动态规划).md +++ b/problems/0053.最大子序和(动态规划).md @@ -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; +}; +``` + ----------------------- diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index ccf6f471..0d79fdf9 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -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: diff --git a/problems/0055.跳跃游戏.md b/problems/0055.跳跃游戏.md index 17a3b4f4..6fa83495 100644 --- a/problems/0055.跳跃游戏.md +++ b/problems/0055.跳跃游戏.md @@ -7,7 +7,7 @@ # 55. 跳跃游戏 -[力扣题目链接](https://leetcode-cn.com/problems/jump-game/) +[力扣题目链接](https://leetcode.cn/problems/jump-game/) 给定一个非负整数数组,你最初位于数组的第一个位置。 diff --git a/problems/0056.合并区间.md b/problems/0056.合并区间.md index 92b66473..34d8dd82 100644 --- a/problems/0056.合并区间.md +++ b/problems/0056.合并区间.md @@ -7,7 +7,7 @@ # 56. 合并区间 -[力扣题目链接](https://leetcode-cn.com/problems/merge-intervals/) +[力扣题目链接](https://leetcode.cn/problems/merge-intervals/) 给出一个区间的集合,请合并所有重叠的区间。 @@ -96,7 +96,7 @@ public: vector> merge(vector>& intervals) { vector> result; if (intervals.size() == 0) return result; - // 排序的参数使用了lamda表达式 + // 排序的参数使用了lambda表达式 sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b){return a[0] < b[0];}); result.push_back(intervals[0]); diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index 93735895..bf0a279e 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -8,7 +8,7 @@ ## 59.螺旋矩阵II -[力扣题目链接](https://leetcode-cn.com/problems/spiral-matrix-ii/) +[力扣题目链接](https://leetcode.cn/problems/spiral-matrix-ii/) 给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 @@ -24,6 +24,8 @@ ## 思路 +为了利于录友们理解,我特意录制了视频,[拿下螺旋矩阵,《代码随想录》第五题!](https://www.bilibili.com/video/BV1SL4y1N7mV),结合本篇文章一起看,效果更佳。 + 这道题目可以说在面试中出现频率较高的题目,**本题并不涉及到什么算法,就是模拟过程,但却十分考察对代码的掌控能力。** 要如何画出这个螺旋排列的正方形矩阵呢? @@ -74,7 +76,7 @@ public: int loop = n / 2; // 每个圈循环几次,例如n为奇数3,那么loop = 1 只是循环一圈,矩阵中间的值需要单独处理 int mid = n / 2; // 矩阵中间的位置,例如:n为3, 中间的位置就是(1,1),n为5,中间位置为(2, 2) int count = 1; // 用来给矩阵中每一个空格赋值 - int offset = 1; // 每一圈循环,需要控制每一条边遍历的长度 + int offset = 1; // 需要控制每一条边遍历的长度,每次循环右边界收缩一位 int i,j; while (loop --) { i = startx; @@ -82,11 +84,11 @@ public: // 下面开始的四个for就是模拟转了一圈 // 模拟填充上行从左到右(左闭右开) - for (j = starty; j < starty + n - offset; j++) { + for (j = starty; j < n - offset; j++) { res[startx][j] = count++; } // 模拟填充右列从上到下(左闭右开) - for (i = startx; i < startx + n - offset; i++) { + for (i = startx; i < n - offset; i++) { res[i][j] = count++; } // 模拟填充下行从右到左(左闭右开) @@ -103,7 +105,7 @@ public: starty++; // offset 控制每一圈里每一条边遍历的长度 - offset += 2; + offset += 1; } // 如果n为奇数的话,需要单独给矩阵最中间的位置赋值 @@ -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; 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 + } +} +``` -----------------------
diff --git a/problems/0062.不同路径.md b/problems/0062.不同路径.md index f59b7be8..02bcc2ae 100644 --- a/problems/0062.不同路径.md +++ b/problems/0062.不同路径.md @@ -6,7 +6,7 @@ # 62.不同路径 -[力扣题目链接](https://leetcode-cn.com/problems/unique-paths/) +[力扣题目链接](https://leetcode.cn/problems/unique-paths/) 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。 diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index d09ea0e6..ca34055a 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -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> dp(m, vector(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>& 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> dp(m, vector(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; diff --git a/problems/0070.爬楼梯.md b/problems/0070.爬楼梯.md index 34d41441..c92c581c 100644 --- a/problems/0070.爬楼梯.md +++ b/problems/0070.爬楼梯.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

# 70. 爬楼梯 -[力扣题目链接](https://leetcode-cn.com/problems/climbing-stairs/) +[力扣题目链接](https://leetcode.cn/problems/climbing-stairs/) 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index 0f482bb7..ec019e57 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -11,7 +11,7 @@ ## 70. 爬楼梯 -[力扣题目链接](https://leetcode-cn.com/problems/climbing-stairs/) +[力扣题目链接](https://leetcode.cn/problems/climbing-stairs/) 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md index 3802c228..641d3128 100644 --- a/problems/0072.编辑距离.md +++ b/problems/0072.编辑距离.md @@ -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]; +}; +``` + + + -----------------------
diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 9e0398ab..8d22d018 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -9,7 +9,7 @@ # 第77题. 组合 -[力扣题目链接](https://leetcode-cn.com/problems/combinations/ ) +[力扣题目链接](https://leetcode.cn/problems/combinations/ ) 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index 94608ec1..a6767047 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -14,7 +14,7 @@ 文中的回溯法是可以剪枝优化的,本篇我们继续来看一下题目77. 组合。 -链接:https://leetcode-cn.com/problems/combinations/ +链接:https://leetcode.cn/problems/combinations/ **看本篇之前,需要先看[回溯算法:求组合问题!](https://programmercarl.com/0077.组合.html)**。 diff --git a/problems/0078.子集.md b/problems/0078.子集.md index e1c52b5b..3d850c08 100644 --- a/problems/0078.子集.md +++ b/problems/0078.子集.md @@ -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++) { diff --git a/problems/0084.柱状图中最大的矩形.md b/problems/0084.柱状图中最大的矩形.md index 439a3bc5..e085e455 100644 --- a/problems/0084.柱状图中最大的矩形.md +++ b/problems/0084.柱状图中最大的矩形.md @@ -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; +}; +``` + + + -----------------------
diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 74ce000b..909c5692 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -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++) { diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 6401824b..41940487 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -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); diff --git a/problems/0096.不同的二叉搜索树.md b/problems/0096.不同的二叉搜索树.md index 25561b50..9d98c62d 100644 --- a/problems/0096.不同的二叉搜索树.md +++ b/problems/0096.不同的二叉搜索树.md @@ -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 为节点组成的二叉搜索树有多少种? diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index a8f3c324..61dd5427 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -7,7 +7,7 @@ # 98.验证二叉搜索树 -[力扣题目链接](https://leetcode-cn.com/problems/validate-binary-search-tree/) +[力扣题目链接](https://leetcode.cn/problems/validate-binary-search-tree/) 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 diff --git a/problems/0100.相同的树.md b/problems/0100.相同的树.md index 5e805d01..5288779b 100644 --- a/problems/0100.相同的树.md +++ b/problems/0100.相同的树.md @@ -8,7 +8,7 @@ # 100. 相同的树 -[力扣题目链接](https://leetcode-cn.com/problems/same-tree/) +[力扣题目链接](https://leetcode.cn/problems/same-tree/) 给定两个二叉树,编写一个函数来检验它们是否相同。 diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 1eb43589..40249bb7 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -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) + } +} +``` + -----------------------
diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index ab8f2e57..a2717d09 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -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>& result, int depth) + { + if (cur == nullptr) return; + if (result.size() == depth) result.push_back(vector()); + result[depth].push_back(cur->val); + order(cur->left, result, depth + 1); + order(cur->right, result, depth + 1); + } + vector> levelOrder(TreeNode* root) { + vector> 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>>) -> Vec> { + 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>>) -> Vec> { + 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转换为List,return关键字可以省略 + } +} +``` + # 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 // 最后需要转换为Array,return关键字可以省略 + } +} +``` # 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 + } +} +``` # 总结 diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 2229a854..ed27f95d 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -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>>) -> 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 + } +} +``` + -----------------------
diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 188ad3cb..6d87c756 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -12,7 +12,7 @@ # 106.从中序与后序遍历序列构造二叉树 -[力扣题目链接](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) +[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) 根据一棵树的中序遍历与后序遍历构造二叉树。 @@ -394,7 +394,7 @@ public: # 105.从前序与中序遍历序列构造二叉树 -[力扣题目链接](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) +[力扣题目链接](https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) 根据一棵树的前序遍历与中序遍历构造二叉树。 @@ -1091,7 +1091,53 @@ class Solution_0106 { } ``` +## Scala +106 从中序与后序遍历序列构造二叉树 + +```scala +object Solution { + def buildTree(inorder: Array[Int], postorder: Array[Int]): TreeNode = { + // 1、如果长度为0,则直接返回null + var len = inorder.size + if (len == 0) return null + // 2、后序数组的最后一个元素是当前根元素 + var rootValue = postorder(len - 1) + var root: TreeNode = new TreeNode(rootValue, null, null) + if (len == 1) return root // 如果数组只有一个节点,就直接返回 + // 3、在中序数组中找到切割点的索引 + var delimiterIndex: Int = inorder.indexOf(rootValue) + // 4、切分数组往下迭代 + root.left = buildTree(inorder.slice(0, delimiterIndex), postorder.slice(0, delimiterIndex)) + root.right = buildTree(inorder.slice(delimiterIndex + 1, len), postorder.slice(delimiterIndex, len - 1)) + root // 返回root,return关键字可以省略 + } +} +``` + +105 从前序与中序遍历序列构造二叉树 + +```scala +object Solution { + def buildTree(preorder: Array[Int], inorder: Array[Int]): TreeNode = { + // 1、如果长度为0,直接返回空 + var len = inorder.size + if (len == 0) return null + // 2、前序数组的第一个元素是当前子树根节点 + var rootValue = preorder(0) + var root = new TreeNode(rootValue, null, null) + if (len == 1) return root // 如果数组元素只有一个,那么返回根节点 + // 3、在中序数组中,找到切割点 + var delimiterIndex = inorder.indexOf(rootValue) + + // 4、切分数组往下迭代 + root.left = buildTree(preorder.slice(1, delimiterIndex + 1), inorder.slice(0, delimiterIndex)) + root.right = buildTree(preorder.slice(delimiterIndex + 1, preorder.size), inorder.slice(delimiterIndex + 1, len)) + + root + } +} +``` -----------------------
diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index 6ee3947b..c9c1a693 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -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/) 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index d98ff8a9..3aa815ab 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -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; diff --git a/problems/0111.二叉树的最小深度.md b/problems/0111.二叉树的最小深度.md index 224caa5e..0137bd15 100644 --- a/problems/0111.二叉树的最小深度.md +++ b/problems/0111.二叉树的最小深度.md @@ -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>>) -> i32 { + return Solution::bfs(root) + } + + // 递归 + pub fn dfs(node: Option>>) -> 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>>) -> 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 + } + +``` + -----------------------
diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index d3eec16b..d4cb5190 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -16,7 +16,7 @@ # 112. 路径总和 -[力扣题目链接](https://leetcode-cn.com/problems/path-sum/) +[力扣题目链接](https://leetcode.cn/problems/path-sum/) 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 @@ -216,7 +216,7 @@ public: # 113. 路径总和ii -[力扣题目链接](https://leetcode-cn.com/problems/path-sum-ii/) +[力扣题目链接](https://leetcode.cn/problems/path-sum-ii/) 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。 @@ -300,7 +300,7 @@ public: ## java -lc112 +### 0112.路径总和 ```java class solution { public boolean haspathsum(treenode root, int targetsum) { @@ -373,7 +373,7 @@ class solution { ``` -0113.路径总和-ii +### 0113.路径总和-ii ```java class solution { @@ -436,7 +436,7 @@ class Solution { ## python -0112.路径总和 +### 0112.路径总和 **递归** ```python @@ -488,7 +488,7 @@ class solution: return false ``` -0113.路径总和-ii +### 0113.路径总和-ii **递归** ```python @@ -545,7 +545,7 @@ class Solution: ## go -112. 路径总和 +### 112. 路径总和 ```go //递归法 @@ -570,7 +570,7 @@ func hasPathSum(root *TreeNode, targetSum int) bool { } ``` -113. 路径总和 II +### 113. 路径总和 II ```go /** @@ -612,7 +612,7 @@ func traverse(node *TreeNode, result *[][]int, currPath *[]int, targetSum int) { ## javascript -0112.路径总和 +### 0112.路径总和 **递归** ```javascript @@ -673,7 +673,7 @@ let hasPathSum = function(root, targetSum) { }; ``` -0113.路径总和-ii +### 0113.路径总和-ii **递归** ```javascript @@ -768,7 +768,7 @@ let pathSum = function(root, targetSum) { ## TypeScript -> 0112.路径总和 +### 0112.路径总和 **递归法:** @@ -850,7 +850,7 @@ function hasPathSum(root: TreeNode | null, targetSum: number): boolean { }; ``` -> 0112.路径总和 ii +### 0112.路径总和 ii **递归法:** @@ -888,7 +888,7 @@ function pathSum(root: TreeNode | null, targetSum: number): number[][] { ## Swift -0112.路径总和 +### 0112.路径总和 **递归** @@ -955,7 +955,7 @@ func hasPathSum(_ root: TreeNode?, _ targetSum: Int) -> Bool { } ``` -0113.路径总和 II +### 0113.路径总和 II **递归** @@ -1126,7 +1126,90 @@ int** pathSum(struct TreeNode* root, int targetSum, int* returnSize, int** retur } ``` +## Scala +### 0112.路径总和 + +**递归:** +```scala +object Solution { + def hasPathSum(root: TreeNode, targetSum: Int): Boolean = { + if(root == null) return false + var res = false + + def traversal(curNode: TreeNode, sum: Int): Unit = { + if (res) return // 如果直接标记为true了,就没有往下递归的必要了 + if (curNode.left == null && curNode.right == null && sum == targetSum) { + res = true + return + } + // 往下递归 + if (curNode.left != null) traversal(curNode.left, sum + curNode.left.value) + if (curNode.right != null) traversal(curNode.right, sum + curNode.right.value) + } + + traversal(root, root.value) + res // return关键字可以省略 + } +} +``` + +**迭代:** +```scala +object Solution { + import scala.collection.mutable + def hasPathSum(root: TreeNode, targetSum: Int): Boolean = { + if (root == null) return false + val stack = mutable.Stack[(TreeNode, Int)]() + stack.push((root, root.value)) // 将根节点元素放入stack + while (!stack.isEmpty) { + val curNode = stack.pop() // 取出栈顶元素 + // 如果遇到叶子节点,看当前的值是否等于targetSum,等于则返回true + if (curNode._1.left == null && curNode._1.right == null && curNode._2 == targetSum) { + return true + } + if (curNode._1.right != null) stack.push((curNode._1.right, curNode._2 + curNode._1.right.value)) + if (curNode._1.left != null) stack.push((curNode._1.left, curNode._2 + curNode._1.left.value)) + } + false //如果没有返回true,即可返回false,return关键字可以省略 + } +} +``` + +### 0113.路径总和 II + +**递归:** +```scala +object Solution { + import scala.collection.mutable.ListBuffer + def pathSum(root: TreeNode, targetSum: Int): List[List[Int]] = { + val res = ListBuffer[List[Int]]() + if (root == null) return res.toList + val path = ListBuffer[Int](); + + def traversal(cur: TreeNode, count: Int): Unit = { + if (cur.left == null && cur.right == null && count == 0) { + res.append(path.toList) + return + } + if (cur.left != null) { + path.append(cur.left.value) + traversal(cur.left, count - cur.left.value) + path.remove(path.size - 1) + } + if (cur.right != null) { + path.append(cur.right.value) + traversal(cur.right, count - cur.right.value) + path.remove(path.size - 1) + } + } + + path.append(root.value) + traversal(root, targetSum - root.value) + res.toList + } +} +``` -----------------------
diff --git a/problems/0115.不同的子序列.md b/problems/0115.不同的子序列.md index 0f762969..9ae04139 100644 --- a/problems/0115.不同的子序列.md +++ b/problems/0115.不同的子序列.md @@ -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]; +}; +``` + + + -----------------------
diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index 2c443de5..ed8ce592 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -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/) 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index f0bc3b97..a577f1dd 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -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]; +}; +``` + + + -----------------------
diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 1e7b77d8..b9fa8386 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -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 天的价格。 diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 5a165a14..fa9f8842 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -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; +}; +``` + ----------------------- diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 56ade343..c15aaee8 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -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: > 版本一: diff --git a/problems/0127.单词接龙.md b/problems/0127.单词接龙.md index 584bcb2a..f1c6f182 100644 --- a/problems/0127.单词接龙.md +++ b/problems/0127.单词接龙.md @@ -7,7 +7,7 @@ # 127. 单词接龙 -[力扣题目链接](https://leetcode-cn.com/problems/word-ladder/) +[力扣题目链接](https://leetcode.cn/problems/word-ladder/) 字典 wordList 中从单词 beginWord 和 endWord 的 转换序列 是一个按下述规格形成的序列: * 序列中第一个单词是 beginWord 。 diff --git a/problems/0129.求根到叶子节点数字之和.md b/problems/0129.求根到叶子节点数字之和.md index b271ca7d..ea3845b7 100644 --- a/problems/0129.求根到叶子节点数字之和.md +++ b/problems/0129.求根到叶子节点数字之和.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

# 129. 求根节点到叶节点数字之和 -[力扣题目链接](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/) +[力扣题目链接](https://leetcode.cn/problems/sum-root-to-leaf-numbers/) # 思路 diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 7a702898..a371864d 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -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(); } diff --git a/problems/0132.分割回文串II.md b/problems/0132.分割回文串II.md index 87d3e4b4..92f9b602 100644 --- a/problems/0132.分割回文串II.md +++ b/problems/0132.分割回文串II.md @@ -8,7 +8,7 @@ # 132. 分割回文串 II -[力扣题目链接](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) +[力扣题目链接](https://leetcode.cn/problems/palindrome-partitioning-ii/) 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 diff --git a/problems/0134.加油站.md b/problems/0134.加油站.md index a88f677d..e6dec44b 100644 --- a/problems/0134.加油站.md +++ b/problems/0134.加油站.md @@ -7,7 +7,7 @@ # 134. 加油站 -[力扣题目链接](https://leetcode-cn.com/problems/gas-station/) +[力扣题目链接](https://leetcode.cn/problems/gas-station/) 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 diff --git a/problems/0135.分发糖果.md b/problems/0135.分发糖果.md index 3456a04c..55c2efc7 100644 --- a/problems/0135.分发糖果.md +++ b/problems/0135.分发糖果.md @@ -7,7 +7,7 @@ # 135. 分发糖果 -[力扣题目链接](https://leetcode-cn.com/problems/candy/) +[力扣题目链接](https://leetcode.cn/problems/candy/) 老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 5b4e92b9..7ff13f72 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -8,7 +8,7 @@ ## 139.单词拆分 -[力扣题目链接](https://leetcode-cn.com/problems/word-break/) +[力扣题目链接](https://leetcode.cn/problems/word-break/) 给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。 diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index e8ca950d..6b7c7e66 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -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 + } +} +``` -----------------------
diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index fd3d69aa..05916135 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -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 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() + } +} +``` -----------------------
diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d03de421..38372f91 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -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 ; +} +``` ----------------------- diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 61c558a1..7ff19852 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -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]; +}; +``` + + + -----------------------
diff --git a/problems/0189.旋转数组.md b/problems/0189.旋转数组.md index 3ffed877..23092f9c 100644 --- a/problems/0189.旋转数组.md +++ b/problems/0189.旋转数组.md @@ -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--; + } +} +``` + ----------------------- diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index a828b9a9..ad660f27 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -6,7 +6,7 @@ ## 198.打家劫舍 -[力扣题目链接](https://leetcode-cn.com/problems/house-robber/) +[力扣题目链接](https://leetcode.cn/problems/house-robber/) 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 741a735a..0bea0c72 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -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 set = new HashSet(); + while(n != 1 && !set.Contains(n)) { //判断避免循环 + set.Add(n); + n = getSum(n); + } + return n == 1; + } +} +``` -----------------------
diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index 751553e2..b79d29a5 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -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 + } +} +``` -----------------------
diff --git a/problems/0205.同构字符串.md b/problems/0205.同构字符串.md index d4b71c59..284e7fd9 100644 --- a/problems/0205.同构字符串.md +++ b/problems/0205.同构字符串.md @@ -7,7 +7,7 @@ # 205. 同构字符串 -[力扣题目链接](https://leetcode-cn.com/problems/isomorphic-strings/) +[力扣题目链接](https://leetcode.cn/problems/isomorphic-strings/) 给定两个字符串 s 和 t,判断它们是否是同构的。 diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 941928ba..24ec7b94 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -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是当前节点 + } + +} +``` -----------------------
diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index fbef7692..e2eb378e 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -5,9 +5,9 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

-## 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, 数组是 2,3,1,2,4,3,来看一下查找的过程: ![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/) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 9e698d01..d6b53a24 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -6,7 +6,7 @@ ## 213.打家劫舍II -[力扣题目链接](https://leetcode-cn.com/problems/house-robber-ii/) +[力扣题目链接](https://leetcode.cn/problems/house-robber-ii/) 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。 diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 32b1347e..0ace0fd5 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -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; }; ``` diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index ba7acc5a..e2825cfb 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -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 + } +} +``` + -----------------------
diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 3457c4b3..40415d8d 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -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(); + } +} +``` -----------------------
diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index a3ebe24d..8e35fc9d 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -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 + } +} +``` + -----------------------
diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 1a56d9f3..4662e2f2 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -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 + } + +} +``` -----------------------
diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index db910d4e..f591fcef 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -7,7 +7,7 @@ # 234.回文链表 -[力扣题目链接](https://leetcode-cn.com/problems/palindrome-linked-list/) +[力扣题目链接](https://leetcode.cn/problems/palindrome-linked-list/) 请判断一个链表是否为回文链表。 diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index f7f1427a..9ff7e293 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -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/) 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 69a6d0d6..23695b11 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -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/) 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index f269450f..23e79c80 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -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 + } + // 最终返回res,return关键字可以省略 + 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 +} +``` -----------------------
diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 080166fd..8f4b5ae2 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -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字符串单词对应的记录+=1,t字符串对应的记录-=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,说明匹配成功,返回true,return可以省略 + 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.赎金信 diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index 1362897c..d84cc6e1 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -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 + } +} +``` + -----------------------
diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index 5b15639c..e8ec98c6 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -7,7 +7,7 @@ ## 279.完全平方数 -[力扣题目链接](https://leetcode-cn.com/problems/perfect-squares/) +[力扣题目链接](https://leetcode.cn/problems/perfect-squares/) 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 diff --git a/problems/0283.移动零.md b/problems/0283.移动零.md index ed59d2c4..fe8e41c1 100644 --- a/problems/0283.移动零.md +++ b/problems/0283.移动零.md @@ -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; + } +}; +``` + + + -----------------------
diff --git a/problems/0300.最长上升子序列.md b/problems/0300.最长上升子序列.md index cfa8ae12..41c6a7ce 100644 --- a/problems/0300.最长上升子序列.md +++ b/problems/0300.最长上升子序列.md @@ -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; +}; +``` + diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index f3e7541b..229fc636 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -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]); +}; +``` + + + -----------------------
diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index fc0490c8..03c6a4e2 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -7,7 +7,7 @@ ## 322. 零钱兑换 -[力扣题目链接](https://leetcode-cn.com/problems/coin-change/) +[力扣题目链接](https://leetcode.cn/problems/coin-change/) 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index c71b2a93..71942c79 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -9,7 +9,7 @@ # 332.重新安排行程 -[力扣题目链接](https://leetcode-cn.com/problems/reconstruct-itinerary/) +[力扣题目链接](https://leetcode.cn/problems/reconstruct-itinerary/) 给定一个机票的字符串二维数组 [from, to],子数组中的两个成员分别表示飞机出发和降落的机场地点,对该行程进行重新规划排序。所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。 diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index a4d8f6b2..d2add232 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -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 = 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) diff --git a/problems/0343.整数拆分.md b/problems/0343.整数拆分.md index 279f1d71..dd03937f 100644 --- a/problems/0343.整数拆分.md +++ b/problems/0343.整数拆分.md @@ -6,7 +6,7 @@ # 343. 整数拆分 -[力扣题目链接](https://leetcode-cn.com/problems/integer-break/) +[力扣题目链接](https://leetcode.cn/problems/integer-break/) 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index 58bada05..aba6e2f3 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -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 + } + } +} +``` -----------------------
diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 1d6a358b..a04041cc 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -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) + } +} +``` -----------------------
diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 45f19b6e..98518647 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -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 one = Insert(nums1); + HashSet two = Insert(nums2); + one.IntersectWith(two); + return one.ToArray(); + } + public HashSet Insert(int[] nums){ + HashSet one = new HashSet(); + foreach(int num in nums){ + one.Add(num); + } + return one; + } + +``` ## 相关题目 * 350.两个数组的交集 II diff --git a/problems/0376.摆动序列.md b/problems/0376.摆动序列.md index 6822896e..00f8f70c 100644 --- a/problems/0376.摆动序列.md +++ b/problems/0376.摆动序列.md @@ -9,7 +9,7 @@ # 376. 摆动序列 -[力扣题目链接](https://leetcode-cn.com/problems/wiggle-subsequence/) +[力扣题目链接](https://leetcode.cn/problems/wiggle-subsequence/) 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。 diff --git a/problems/0377.组合总和Ⅳ.md b/problems/0377.组合总和Ⅳ.md index 1d808a3a..f8e544a9 100644 --- a/problems/0377.组合总和Ⅳ.md +++ b/problems/0377.组合总和Ⅳ.md @@ -8,7 +8,7 @@ ## 377. 组合总和 Ⅳ -[力扣题目链接](https://leetcode-cn.com/problems/combination-sum-iv/) +[力扣题目链接](https://leetcode.cn/problems/combination-sum-iv/) 难度:中等 diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 6177cc41..3cde5472 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -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 + } + // 定义map,key是字符,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; + } + +``` -----------------------
diff --git a/problems/0392.判断子序列.md b/problems/0392.判断子序列.md index 671576f7..9a26d639 100644 --- a/problems/0392.判断子序列.md +++ b/problems/0392.判断子序列.md @@ -7,7 +7,7 @@ ## 392.判断子序列 -[力扣题目链接](https://leetcode-cn.com/problems/is-subsequence/) +[力扣题目链接](https://leetcode.cn/problems/is-subsequence/) 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 @@ -201,7 +201,32 @@ const isSubsequence = (s, t) => { }; ``` +TypeScript: + +```typescript +function isSubsequence(s: string, t: string): boolean { + /** + dp[i][j]: s的前i-1个,t的前j-1个,最长公共子序列的长度 + */ + 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 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] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[sLen][tLen] === s.length; +}; +``` + Go: + ```go func isSubsequence(s string, t string) bool { dp := make([][]int,len(s)+1) diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index d7fd629e..8485cdac 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -7,7 +7,7 @@ # 404.左叶子之和 -[力扣题目链接](https://leetcode-cn.com/problems/sum-of-left-leaves/) +[力扣题目链接](https://leetcode.cn/problems/sum-of-left-leaves/) 计算给定二叉树的所有左叶子之和。 @@ -336,8 +336,8 @@ var sumOfLeftLeaves = function(root) { if(node===null){ return 0; } - let leftValue = sumOfLeftLeaves(node.left); - let rightValue = sumOfLeftLeaves(node.right); + let leftValue = nodesSum(node.left); + let rightValue = nodesSum(node.right); // 3. 单层递归逻辑 let midValue = 0; if(node.left&&node.left.left===null&&node.left.right===null){ @@ -516,6 +516,44 @@ int sumOfLeftLeaves(struct TreeNode* root){ } ``` +## Scala + +**递归:** +```scala +object Solution { + def sumOfLeftLeaves(root: TreeNode): Int = { + if(root == null) return 0 + var midValue = 0 + if(root.left != null && root.left.left == null && root.left.right == null){ + midValue = root.left.value + } + // return关键字可以省略 + midValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right) + } +} +``` + +**迭代:** +```scala +object Solution { + import scala.collection.mutable + def sumOfLeftLeaves(root: TreeNode): Int = { + val stack = mutable.Stack[TreeNode]() + if (root == null) return 0 + stack.push(root) + var sum = 0 + while (!stack.isEmpty) { + val curNode = stack.pop() + if (curNode.left != null && curNode.left.left == null && curNode.left.right == null) { + sum += curNode.left.value // 如果满足条件就累加 + } + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + } + sum + } +} +``` -----------------------
diff --git a/problems/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index 641086a9..879820ea 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -7,7 +7,7 @@ # 406.根据身高重建队列 -[力扣题目链接](https://leetcode-cn.com/problems/queue-reconstruction-by-height/) +[力扣题目链接](https://leetcode.cn/problems/queue-reconstruction-by-height/) 假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。 diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index eb6601e1..5419fc1f 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -6,7 +6,7 @@ ## 416. 分割等和子集 -[力扣题目链接](https://leetcode-cn.com/problems/partition-equal-subset-sum/) +[力扣题目链接](https://leetcode.cn/problems/partition-equal-subset-sum/) 题目难易:中等 @@ -417,6 +417,26 @@ var canPartition = function(nums) { ``` +TypeScript: + +```ts +function canPartition(nums: number[]): boolean { + const sum: number = nums.reduce((a: number, b: number): number => a + b); + if (sum % 2 === 1) return false; + const target: number = sum / 2; + // dp[j]表示容量(总数和)为j的背包所能装下的数(下标[0, i]之间任意取)的总和(<= 容量)的最大值 + const dp: number[] = new Array(target + 1).fill(0); + const n: number = nums.length; + for (let i: number = 0; i < n; i++) { + for (let j: number = target; j >= nums[i]; j--) { + dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]); + } + } + return dp[target] === target; +}; +``` + + C: 二维dp: ```c @@ -575,6 +595,5 @@ function canPartition(nums: number[]): boolean { - -----------------------
diff --git a/problems/0435.无重叠区间.md b/problems/0435.无重叠区间.md index 66aa1244..f1e259ae 100644 --- a/problems/0435.无重叠区间.md +++ b/problems/0435.无重叠区间.md @@ -7,7 +7,7 @@ # 435. 无重叠区间 -[力扣题目链接](https://leetcode-cn.com/problems/non-overlapping-intervals/) +[力扣题目链接](https://leetcode.cn/problems/non-overlapping-intervals/) 给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。 diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index e8f7e54c..aca9084f 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -9,7 +9,7 @@ # 450.删除二叉搜索树中的节点 -[力扣题目链接]( https://leetcode-cn.com/problems/delete-node-in-a-bst/) +[力扣题目链接]( https://leetcode.cn/problems/delete-node-in-a-bst/) 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。 diff --git a/problems/0452.用最少数量的箭引爆气球.md b/problems/0452.用最少数量的箭引爆气球.md index d4bbe961..e593b876 100644 --- a/problems/0452.用最少数量的箭引爆气球.md +++ b/problems/0452.用最少数量的箭引爆气球.md @@ -7,7 +7,7 @@ # 452. 用最少数量的箭引爆气球 -[力扣题目链接](https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/) +[力扣题目链接](https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/) 在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以纵坐标并不重要,因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。 diff --git a/problems/0454.四数相加II.md b/problems/0454.四数相加II.md index a6cd413b..d22e2335 100644 --- a/problems/0454.四数相加II.md +++ b/problems/0454.四数相加II.md @@ -9,7 +9,7 @@ # 第454题.四数相加II -[力扣题目链接](https://leetcode-cn.com/problems/4sum-ii/) +[力扣题目链接](https://leetcode.cn/problems/4sum-ii/) 给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。 @@ -318,5 +318,70 @@ impl Solution { } ``` + +Scala: +```scala +object Solution { + // 导包 + import scala.collection.mutable + def fourSumCount(nums1: Array[Int], nums2: Array[Int], nums3: Array[Int], nums4: Array[Int]): Int = { + // 定义一个HashMap,key存储值,value存储该值出现的次数 + val map = new mutable.HashMap[Int, Int]() + // 遍历前两个数组,把他们所有可能的情况都记录到map + for (i <- nums1.indices) { + for (j <- nums2.indices) { + val tmp = nums1(i) + nums2(j) + // 如果包含该值,则对他的key加1,不包含则添加进去 + if (map.contains(tmp)) { + map.put(tmp, map.get(tmp).get + 1) + } else { + map.put(tmp, 1) + } + } + } + var res = 0 // 结果变量 + // 遍历后两个数组 + for (i <- nums3.indices) { + for (j <- nums4.indices) { + val tmp = -(nums3(i) + nums4(j)) + // 如果map中存在该值,结果就+=value + if (map.contains(tmp)) { + res += map.get(tmp).get + } + } + } + // 返回最终结果,可以省略关键字return + res + } +} +``` + +C#: +```csharp +public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { + Dictionary dic = new Dictionary(); + foreach(var i in nums1){ + foreach(var j in nums2){ + int sum = i + j; + if(dic.ContainsKey(sum)){ + dic[sum]++; + }else{ + dic.Add(sum, 1); + } + + } + } + int res = 0; + foreach(var a in nums3){ + foreach(var b in nums4){ + int sum = a+b; + if(dic.TryGetValue(-sum, out var result)){ + res += result; + } + } + } + return res; + } +``` -----------------------
diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 17db4a85..b787dee6 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -7,7 +7,7 @@ # 455.分发饼干 -[力扣题目链接](https://leetcode-cn.com/problems/assign-cookies/) +[力扣题目链接](https://leetcode.cn/problems/assign-cookies/) 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 diff --git a/problems/0459.重复的子字符串.md b/problems/0459.重复的子字符串.md index a51c68ee..bb55bd7c 100644 --- a/problems/0459.重复的子字符串.md +++ b/problems/0459.重复的子字符串.md @@ -11,7 +11,7 @@ # 459.重复的子字符串 -[力扣题目链接](https://leetcode-cn.com/problems/repeated-substring-pattern/) +[力扣题目链接](https://leetcode.cn/problems/repeated-substring-pattern/) 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。 diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index 9911dfe5..ea038140 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

# 463. 岛屿的周长 -[力扣题目链接](https://leetcode-cn.com/problems/island-perimeter/) +[力扣题目链接](https://leetcode.cn/problems/island-perimeter/) ## 思路 diff --git a/problems/0474.一和零.md b/problems/0474.一和零.md index d38ce03f..a5018baf 100644 --- a/problems/0474.一和零.md +++ b/problems/0474.一和零.md @@ -7,7 +7,7 @@ ## 474.一和零 -[力扣题目链接](https://leetcode-cn.com/problems/ones-and-zeroes/) +[力扣题目链接](https://leetcode.cn/problems/ones-and-zeroes/) 给你一个二进制字符串数组 strs 和两个整数 m 和 n 。 diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 3ea2382b..291a19bd 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -9,7 +9,7 @@ # 491.递增子序列 -[力扣题目链接](https://leetcode-cn.com/problems/increasing-subsequences/) +[力扣题目链接](https://leetcode.cn/problems/increasing-subsequences/) 给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。 diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 8ce1f6f1..8f116fae 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -7,7 +7,7 @@ ## 494. 目标和 -[力扣题目链接](https://leetcode-cn.com/problems/target-sum/) +[力扣题目链接](https://leetcode.cn/problems/target-sum/) 难度:中等 @@ -351,22 +351,26 @@ const findTargetSumWays = (nums, target) => { }; ``` -TypeScript: -```typescript +TypeScript: + +```ts function findTargetSumWays(nums: number[], target: number): number { - const sum: number = nums.reduce((pre, cur) => pre + cur); - if (Math.abs(target) > sum) return 0; - if ((target + sum) % 2 === 1) return 0; - const bagSize: number = (target + sum) / 2; - const dp: number[] = new Array(bagSize + 1).fill(0); - dp[0] = 1; - for (let i = 0; i < nums.length; i++) { - for (let j = bagSize; j >= nums[i]; j--) { + // 把数组分成两个组合left, right.left + right = sum, left - right = target. + const sum: number = nums.reduce((a: number, b: number): number => a + b); + if ((sum + target) % 2 || Math.abs(target) > sum) return 0; + const left: number = (sum + target) / 2; + + // 将问题转化为装满容量为left的背包有多少种方法 + // dp[i]表示装满容量为i的背包有多少种方法 + const dp: number[] = new Array(left + 1).fill(0); + dp[0] = 1; // 装满容量为0的背包有1种方法(什么也不装) + for (let i: number = 0; i < nums.length; i++) { + for (let j: number = left; j >= nums[i]; j--) { dp[j] += dp[j - nums[i]]; } } - return dp[bagSize]; + return dp[left]; }; ``` diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index 02339677..3c948815 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -6,7 +6,7 @@ # 496.下一个更大元素 I -[力扣题目链接](https://leetcode-cn.com/problems/next-greater-element-i/) +[力扣题目链接](https://leetcode.cn/problems/next-greater-element-i/) 给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。 @@ -332,5 +332,36 @@ var nextGreaterElement = function (nums1, nums2) { }; ``` +TypeScript: + +```typescript +function nextGreaterElement(nums1: number[], nums2: number[]): number[] { + const resArr: number[] = new Array(nums1.length).fill(-1); + const stack: number[] = []; + const helperMap: Map = new Map(); + nums1.forEach((num, index) => { + helperMap.set(num, index); + }) + stack.push(0); + for (let i = 1, length = nums2.length; i < length; i++) { + let top = stack[stack.length - 1]; + while (stack.length > 0 && nums2[top] < nums2[i]) { + let index = helperMap.get(nums2[top]); + if (index !== undefined) { + resArr[index] = nums2[i]; + } + stack.pop(); + top = stack[stack.length - 1]; + } + if (helperMap.get(nums2[i]) !== undefined) { + stack.push(i); + } + } + return resArr; +}; +``` + + + -----------------------
diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 9cb5d071..f22f1eb3 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -9,7 +9,7 @@ # 501.二叉搜索树中的众数 -[力扣题目链接](https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/solution/) +[力扣题目链接](https://leetcode.cn/problems/find-mode-in-binary-search-tree/solution/) 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。 diff --git a/problems/0503.下一个更大元素II.md b/problems/0503.下一个更大元素II.md index ace4d40b..0bd0fb82 100644 --- a/problems/0503.下一个更大元素II.md +++ b/problems/0503.下一个更大元素II.md @@ -6,7 +6,7 @@ # 503.下一个更大元素II -[力扣题目链接](https://leetcode-cn.com/problems/next-greater-element-ii/) +[力扣题目链接](https://leetcode.cn/problems/next-greater-element-ii/) 给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。 @@ -182,5 +182,31 @@ var nextGreaterElements = function (nums) { return res; }; ``` +TypeScript: + +```typescript +function nextGreaterElements(nums: number[]): number[] { + const length: number = nums.length; + const stack: number[] = []; + stack.push(0); + const resArr: number[] = new Array(length).fill(-1); + for (let i = 1; i < length * 2; i++) { + const index = i % length; + let top = stack[stack.length - 1]; + while (stack.length > 0 && nums[top] < nums[index]) { + resArr[top] = nums[index]; + stack.pop(); + top = stack[stack.length - 1]; + } + if (i < length) { + stack.push(i); + } + } + return resArr; +}; +``` + + + -----------------------
diff --git a/problems/0509.斐波那契数.md b/problems/0509.斐波那契数.md index 1d17784d..785d0125 100644 --- a/problems/0509.斐波那契数.md +++ b/problems/0509.斐波那契数.md @@ -6,7 +6,7 @@ # 509. 斐波那契数 -[力扣题目链接](https://leetcode-cn.com/problems/fibonacci-number/) +[力扣题目链接](https://leetcode.cn/problems/fibonacci-number/) 斐波那契数,通常用 F(n) 表示,形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: F(0) = 0,F(1) = 1 @@ -234,6 +234,7 @@ func fib(n int) int { } ``` ### Javascript +解法一 ```Javascript var fib = function(n) { let dp = [0, 1] @@ -244,6 +245,23 @@ var fib = function(n) { return dp[n] }; ``` +解法二:时间复杂度O(N),空间复杂度O(1) +```Javascript +var fib = function(n) { + // 动规状态转移中,当前结果只依赖前两个元素的结果,所以只要两个变量代替dp数组记录状态过程。将空间复杂度降到O(1) + let pre1 = 1 + let pre2 = 0 + let temp + if (n === 0) return 0 + if (n === 1) return 1 + for(let i = 2; i <= n; i++) { + temp = pre1 + pre1 = pre1 + pre2 + pre2 = temp + } + return pre1 +}; +``` TypeScript diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 12c62c70..817c22c9 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -7,7 +7,7 @@ # 513.找树左下角的值 -[力扣题目链接](https://leetcode-cn.com/problems/find-bottom-left-tree-value/) +[力扣题目链接](https://leetcode.cn/problems/find-bottom-left-tree-value/) 给定一个二叉树,在树的最后一行找到最左边的值。 @@ -546,7 +546,50 @@ func findBottomLeftValue(_ root: TreeNode?) -> Int { } ``` +## Scala +递归版本: +```scala +object Solution { + def findBottomLeftValue(root: TreeNode): Int = { + var maxLeftValue = 0 + var maxLen = Int.MinValue + // 递归方法 + def traversal(node: TreeNode, leftLen: Int): Unit = { + // 如果左右都为空并且当前深度大于最大深度,记录最左节点的值 + if (node.left == null && node.right == null && leftLen > maxLen) { + maxLen = leftLen + maxLeftValue = node.value + } + if (node.left != null) traversal(node.left, leftLen + 1) + if (node.right != null) traversal(node.right, leftLen + 1) + } + traversal(root, 0) // 调用方法 + maxLeftValue // return关键字可以省略 + } +} +``` + +层序遍历: +```scala + import scala.collection.mutable + + def findBottomLeftValue(root: TreeNode): Int = { + val queue = mutable.Queue[TreeNode]() + queue.enqueue(root) + var res = 0 // 记录每层最左侧结果 + while (!queue.isEmpty) { + val len = queue.size + for (i <- 0 until len) { + val curNode = queue.dequeue() + if (i == 0) res = curNode.value // 记录最最左侧的节点 + if (curNode.left != null) queue.enqueue(curNode.left) + if (curNode.right != null) queue.enqueue(curNode.right) + } + } + res // 最终返回结果,return关键字可以省略 + } +``` -----------------------
diff --git a/problems/0516.最长回文子序列.md b/problems/0516.最长回文子序列.md index 69536cef..60d5e920 100644 --- a/problems/0516.最长回文子序列.md +++ b/problems/0516.最长回文子序列.md @@ -5,7 +5,7 @@

参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!

## 516.最长回文子序列 -[力扣题目链接](https://leetcode-cn.com/problems/longest-palindromic-subsequence/) +[力扣题目链接](https://leetcode.cn/problems/longest-palindromic-subsequence/) 给定一个字符串 s ,找到其中最长的回文子序列,并返回该序列的长度。可以假设 s 的最大长度为 1000 。 @@ -186,29 +186,28 @@ class Solution: Go: ```Go func longestPalindromeSubseq(s string) int { - lenth:=len(s) - dp:=make([][]int,lenth) - for i:=0;i b { + return a + } + return b + } + dp := make([][]int, size) + for i := 0; i < size; i++ { + dp[i] = make([]int, size) + dp[i][i] = 1 + } + for i := size - 1; i >= 0; i-- { + for j := i + 1; j < size; j++ { + if s[i] == s[j] { + dp[i][j] = dp[i+1][j-1] + 2 + } else { + dp[i][j] = max(dp[i][j-1], dp[i+1][j]) } } } - for i:=lenth-1;i>=0;i--{ - for j:=i+1;j { }; ``` +TypeScript: + +```typescript +function longestPalindromeSubseq(s: string): number { + /** + dp[i][j]:[i,j]区间内,最长回文子序列的长度 + */ + const length: number = s.length; + const dp: number[][] = new Array(length).fill(0) + .map(_ => new Array(length).fill(0)); + for (let i = 0; i < length; i++) { + dp[i][i] = 1; + } + // 自下而上,自左往右遍历 + for (let i = length - 1; i >= 0; i--) { + for (let j = i + 1; j < length; j++) { + if (s[i] === s[j]) { + dp[i][j] = dp[i + 1][j - 1] + 2; + } else { + dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]); + } + } + } + return dp[0][length - 1]; +}; +``` + + + -----------------------
diff --git a/problems/0518.零钱兑换II.md b/problems/0518.零钱兑换II.md index b6593438..222a10d7 100644 --- a/problems/0518.零钱兑换II.md +++ b/problems/0518.零钱兑换II.md @@ -7,7 +7,7 @@ ## 518. 零钱兑换 II -[力扣题目链接](https://leetcode-cn.com/problems/coin-change-2/) +[力扣题目链接](https://leetcode.cn/problems/coin-change-2/) 难度:中等 diff --git a/problems/0530.二叉搜索树的最小绝对差.md b/problems/0530.二叉搜索树的最小绝对差.md index 77699c9f..cbf8138c 100644 --- a/problems/0530.二叉搜索树的最小绝对差.md +++ b/problems/0530.二叉搜索树的最小绝对差.md @@ -9,7 +9,7 @@ # 530.二叉搜索树的最小绝对差 -[力扣题目链接](https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/) +[力扣题目链接](https://leetcode.cn/problems/minimum-absolute-difference-in-bst/) 给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。 diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 37eb7d0f..853cca6f 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -7,7 +7,7 @@ # 538.把二叉搜索树转换为累加树 -[力扣题目链接](https://leetcode-cn.com/problems/convert-bst-to-greater-tree/) +[力扣题目链接](https://leetcode.cn/problems/convert-bst-to-greater-tree/) 给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。 diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 8c13a390..84061ef5 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -10,7 +10,7 @@ # 541. 反转字符串II -[力扣题目链接](https://leetcode-cn.com/problems/reverse-string-ii/) +[力扣题目链接](https://leetcode.cn/problems/reverse-string-ii/) 给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。 @@ -53,10 +53,10 @@ public: // 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符 if (i + k <= s.size()) { reverse(s.begin() + i, s.begin() + i + k ); - continue; + } else { + // 3. 剩余字符少于 k 个,则将剩余字符全部反转。 + reverse(s.begin() + i, s.end()); } - // 3. 剩余字符少于 k 个,则将剩余字符全部反转。 - reverse(s.begin() + i, s.begin() + s.size()); } return s; } @@ -347,6 +347,47 @@ public class Solution } } ``` +Scala: +版本一: (正常解法) +```scala +object Solution { + def reverseStr(s: String, k: Int): String = { + val res = s.toCharArray // 转换为Array好处理 + for (i <- s.indices by 2 * k) { + // 如果i+k大于了res的长度,则需要全部翻转 + if (i + k > res.length) { + reverse(res, i, s.length - 1) + } else { + reverse(res, i, i + k - 1) + } + } + new String(res) + } + // 翻转字符串,从start到end + def reverse(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 + } + } +} +``` +版本二: 首先利用sliding每隔k个进行分割,随后转换为数组,再使用zipWithIndex添加每个数组的索引,紧接着利用map做变换,如果索引%2==0则说明需要翻转,否则原封不动,最后再转换为String +```scala +object Solution { + def reverseStr(s: String, k: Int): String = { + s.sliding(k, k) + .toArray + .zipWithIndex + .map(v => if (v._2 % 2 == 0) v._1.reverse else v._1) + .mkString + } +} +``` -----------------------
diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md index 53c1a125..fc7e6f39 100644 --- a/problems/0583.两个字符串的删除操作.md +++ b/problems/0583.两个字符串的删除操作.md @@ -6,7 +6,7 @@ ## 583. 两个字符串的删除操作 -[力扣题目链接](https://leetcode-cn.com/problems/delete-operation-for-two-strings/) +[力扣题目链接](https://leetcode.cn/problems/delete-operation-for-two-strings/) 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。 @@ -229,6 +229,67 @@ const minDistance = (word1, word2) => { }; ``` +TypeScript: + +> dp版本一: + +```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]) + 1; + } + } + } + return dp[length1][length2]; +}; +``` + +> dp版本二: + +```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 = 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] + 1; + } else { + dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); + } + } + } + const maxLen: number = dp[length1][length2]; + return length1 + length2 - maxLen * 2; +}; +``` + + + -----------------------
diff --git a/problems/0617.合并二叉树.md b/problems/0617.合并二叉树.md index 55786ea9..40aa98c3 100644 --- a/problems/0617.合并二叉树.md +++ b/problems/0617.合并二叉树.md @@ -7,7 +7,7 @@ # 617.合并二叉树 -[力扣题目链接](https://leetcode-cn.com/problems/merge-two-binary-trees/) +[力扣题目链接](https://leetcode.cn/problems/merge-two-binary-trees/) 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 diff --git a/problems/0647.回文子串.md b/problems/0647.回文子串.md index 913aec65..c0b34e8a 100644 --- a/problems/0647.回文子串.md +++ b/problems/0647.回文子串.md @@ -6,7 +6,7 @@ ## 647. 回文子串 -[力扣题目链接](https://leetcode-cn.com/problems/palindromic-substrings/) +[力扣题目链接](https://leetcode.cn/problems/palindromic-substrings/) 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。 @@ -406,6 +406,63 @@ const countSubstrings = (s) => { } ``` +TypeScript: + +> 动态规划: + +```typescript +function countSubstrings(s: string): number { + /** + dp[i][j]: [i,j]区间内的字符串是否为回文(左闭右闭) + */ + const length: number = s.length; + const dp: boolean[][] = new Array(length).fill(0) + .map(_ => new Array(length).fill(false)); + let resCount: number = 0; + // 自下而上,自左向右遍历 + for (let i = length - 1; i >= 0; i--) { + for (let j = i; j < length; j++) { + if ( + s[i] === s[j] && + (j - i <= 1 || dp[i + 1][j - 1] === true) + ) { + dp[i][j] = true; + resCount++; + } + } + } + return resCount; +}; +``` + +> 双指针法: + +```typescript +function countSubstrings(s: string): number { + const length: number = s.length; + let resCount: number = 0; + for (let i = 0; i < length; i++) { + resCount += expandRange(s, i, i); + resCount += expandRange(s, i, i + 1); + } + return resCount; +}; +function expandRange(s: string, left: number, right: number): number { + let palindromeNum: number = 0; + while ( + left >= 0 && right < s.length && + s[left] === s[right] + ) { + palindromeNum++; + left--; + right++; + } + return palindromeNum; +} +``` + + + -----------------------
diff --git a/problems/0649.Dota2参议院.md b/problems/0649.Dota2参议院.md index 6e84c9fd..f1b3be11 100644 --- a/problems/0649.Dota2参议院.md +++ b/problems/0649.Dota2参议院.md @@ -8,7 +8,7 @@ # 649. Dota2 参议院 -[力扣题目链接](https://leetcode-cn.com/problems/dota2-senate/) +[力扣题目链接](https://leetcode.cn/problems/dota2-senate/) Dota2 的世界里有两个阵营:Radiant(天辉)和 Dire(夜魇) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 1c73354b..38d2a9ec 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -7,7 +7,7 @@ # 654.最大二叉树 -[力扣题目地址](https://leetcode-cn.com/problems/maximum-binary-tree/) +[力扣题目地址](https://leetcode.cn/problems/maximum-binary-tree/) 给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下: diff --git a/problems/0657.机器人能否返回原点.md b/problems/0657.机器人能否返回原点.md index 4eb69a6c..3d91a5c3 100644 --- a/problems/0657.机器人能否返回原点.md +++ b/problems/0657.机器人能否返回原点.md @@ -7,7 +7,7 @@ # 657. 机器人能否返回原点 -[力扣题目链接](https://leetcode-cn.com/problems/robot-return-to-origin/) +[力扣题目链接](https://leetcode.cn/problems/robot-return-to-origin/) 在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。 diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 385b2268..154ba5a9 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -10,7 +10,7 @@ # 669. 修剪二叉搜索树 -[力扣题目链接](https://leetcode-cn.com/problems/trim-a-binary-search-tree/) +[力扣题目链接](https://leetcode.cn/problems/trim-a-binary-search-tree/) 给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。 diff --git a/problems/0673.最长递增子序列的个数.md b/problems/0673.最长递增子序列的个数.md index 9a2c5db2..8a6a2d46 100644 --- a/problems/0673.最长递增子序列的个数.md +++ b/problems/0673.最长递增子序列的个数.md @@ -8,7 +8,7 @@ # 673.最长递增子序列的个数 -[力扣题目链接](https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/) +[力扣题目链接](https://leetcode.cn/problems/number-of-longest-increasing-subsequence/) 给定一个未排序的整数数组,找到最长递增子序列的个数。 diff --git a/problems/0674.最长连续递增序列.md b/problems/0674.最长连续递增序列.md index 4f571d09..5865a68d 100644 --- a/problems/0674.最长连续递增序列.md +++ b/problems/0674.最长连续递增序列.md @@ -6,7 +6,7 @@ ## 674. 最长连续递增序列 -[力扣题目链接](https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence/) +[力扣题目链接](https://leetcode.cn/problems/longest-continuous-increasing-subsequence/) 给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。 @@ -338,6 +338,45 @@ const findLengthOfLCIS = (nums) => { }; ``` +TypeScript: + +> 动态规划: + +```typescript +function findLengthOfLCIS(nums: number[]): number { + /** + dp[i]: 前i个元素,以nums[i]结尾,最长连续子序列的长度 + */ + const dp: number[] = new Array(nums.length).fill(1); + let resMax: number = 1; + for (let i = 1, length = nums.length; i < length; i++) { + if (nums[i] > nums[i - 1]) { + dp[i] = dp[i - 1] + 1; + } + resMax = Math.max(resMax, dp[i]); + } + return resMax; +}; +``` + +> 贪心: + +```typescript +function findLengthOfLCIS(nums: number[]): number { + let resMax: number = 1; + let count: number = 1; + for (let i = 0, length = nums.length; i < length - 1; i++) { + if (nums[i] < nums[i + 1]) { + count++; + } else { + count = 1; + } + resMax = Math.max(resMax, count); + } + return resMax; +}; +``` + diff --git a/problems/0684.冗余连接.md b/problems/0684.冗余连接.md index a16833bc..3928e051 100644 --- a/problems/0684.冗余连接.md +++ b/problems/0684.冗余连接.md @@ -9,7 +9,7 @@ # 684.冗余连接 -[力扣题目链接](https://leetcode-cn.com/problems/redundant-connection/) +[力扣题目链接](https://leetcode.cn/problems/redundant-connection/) 树可以看成是一个连通且 无环 的 无向 图。 diff --git a/problems/0685.冗余连接II.md b/problems/0685.冗余连接II.md index d96d4912..a8da1124 100644 --- a/problems/0685.冗余连接II.md +++ b/problems/0685.冗余连接II.md @@ -7,7 +7,7 @@ # 685.冗余连接II -[力扣题目链接](https://leetcode-cn.com/problems/redundant-connection-ii/) +[力扣题目链接](https://leetcode.cn/problems/redundant-connection-ii/) 在本问题中,有根树指满足以下条件的 有向 图。该树只有一个根节点,所有其他节点都是该根节点的后继。该树除了根节点之外的每一个节点都有且只有一个父节点,而根节点没有父节点。 diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 40cf4ea1..bda400c2 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -7,7 +7,7 @@ # 700.二叉搜索树中的搜索 -[力扣题目地址](https://leetcode-cn.com/problems/search-in-a-binary-search-tree/) +[力扣题目地址](https://leetcode.cn/problems/search-in-a-binary-search-tree/) 给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 50e39ade..102f091e 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -7,7 +7,7 @@ # 701.二叉搜索树中的插入操作 -[力扣题目链接](https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/) +[力扣题目链接](https://leetcode.cn/problems/insert-into-a-binary-search-tree/) 给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证,新值和原始二叉搜索树中的任意节点值都不同。 diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 55625130..6a37e4d1 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -7,7 +7,7 @@ ## 704. 二分查找 -[力扣题目链接](https://leetcode-cn.com/problems/binary-search/) +[力扣题目链接](https://leetcode.cn/problems/binary-search/) 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target  ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。 @@ -36,6 +36,8 @@ ## 思路 +为了易于大家理解,我还录制了视频,可以看这里:[手把手带你撕出正确的二分法](https://www.bilibili.com/video/BV1fA4y1o715) + **这道题目的前提是数组为有序数组**,同时题目还强调**数组中无重复元素**,因为一旦有重复元素,使用二分查找法返回的元素下标可能不是唯一的,这些都是使用二分法的前提条件,当大家看到题目描述满足如上条件的时候,可要想一想是不是可以用二分法了。 二分查找涉及的很多的边界条件,逻辑比较简单,但就是写不好。例如到底是 `while(left < right)` 还是 `while(left <= right)`,到底是`right = middle`呢,还是要`right = middle - 1`呢? @@ -612,5 +614,81 @@ public class Solution{ ``` + +**Kotlin:** +```Kotlin +// (版本一)左闭右开区间 +class Solution { + fun search(nums: IntArray, target: Int): Int { + var left = 0 + var right = nums.size // [left,right) 右侧为开区间,right 设置为 nums.size + while (left < right) { + val mid = (left + right) / 2 + if (nums[mid] < target) left = mid + 1 + else if (nums[mid] > target) right = mid // 代码的核心,循环中 right 是开区间,这里也应是开区间 + else return mid + } + return -1 // 没有找到 target ,返回 -1 + } +} +// (版本二)左闭右闭区间 +class Solution { + fun search(nums: IntArray, target: Int): Int { + var left = 0 + var right = nums.size - 1 // [left,right] 右侧为闭区间,right 设置为 nums.size - 1 + while (left <= right) { + val mid = (left + right) / 2 + if (nums[mid] < target) left = mid + 1 + else if (nums[mid] > target) right = mid - 1 // 代码的核心,循环中 right 是闭区间,这里也应是闭区间 + else return mid + } + return -1 // 没有找到 target ,返回 -1 + } +} +``` +**Scala:** + +(版本一)左闭右闭区间 +```scala +object Solution { + def search(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)) { + right = mid - 1 + } else { + left = mid + 1 + } + } + -1 + } +} +``` +(版本二)左闭右开区间 +```scala +object Solution { + def search(nums: Array[Int], target: Int): Int = { + var left = 0 + var right = nums.length + while (left < right) { + val mid = left + (right - left) / 2 + if (target == nums(mid)) { + return mid + } else if (target < nums(mid)) { + right = mid + } else { + left = mid + 1 + } + } + -1 + } +} +``` + + -----------------------
diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 37ce15ad..6ee11eef 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -9,7 +9,7 @@ # 707.设计链表 -[力扣题目链接](https://leetcode-cn.com/problems/design-linked-list/) +[力扣题目链接](https://leetcode.cn/problems/design-linked-list/) 题意: @@ -1154,7 +1154,75 @@ class MyLinkedList { } ``` +Scala: +```scala +class ListNode(_x: Int = 0, _next: ListNode = null) { + var next: ListNode = _next + var x: Int = _x +} +class MyLinkedList() { + + var size = 0 // 链表尺寸 + var dummy: ListNode = new ListNode(0) // 虚拟头节点 + + // 获取第index个节点的值 + def get(index: Int): Int = { + if (index < 0 || index >= size) { + return -1; + } + var cur = dummy + for (i <- 0 to index) { + cur = cur.next + } + cur.x // 返回cur的值 + } + + // 在链表最前面插入一个节点 + def addAtHead(`val`: Int) { + addAtIndex(0, `val`) + } + + // 在链表最后面插入一个节点 + def addAtTail(`val`: Int) { + addAtIndex(size, `val`) + } + + // 在第index个节点之前插入一个新节点 + // 如果index等于链表长度,则说明新插入的节点是尾巴 + // 如果index等于0,则说明新插入的节点是头 + // 如果index>链表长度,则说明为空 + def addAtIndex(index: Int, `val`: Int) { + if (index > size) { + return + } + var loc = index // 因为参数index是val不可变类型,所以需要赋值给一个可变类型 + if (index < 0) { + loc = 0 + } + size += 1 //链表尺寸+1 + var pre = dummy + for (i <- 0 until loc) { + pre = pre.next + } + val node: ListNode = new ListNode(`val`, pre.next) + pre.next = node + } + // 删除第index个节点 + def deleteAtIndex(index: Int) { + if (index < 0 || index >= size) { + return + } + size -= 1 + var pre = dummy + for (i <- 0 until index) { + pre = pre.next + } + pre.next = pre.next.next + } + +} +``` ----------------------- diff --git a/problems/0714.买卖股票的最佳时机含手续费.md b/problems/0714.买卖股票的最佳时机含手续费.md index b27631c6..7600c52c 100644 --- a/problems/0714.买卖股票的最佳时机含手续费.md +++ b/problems/0714.买卖股票的最佳时机含手续费.md @@ -7,7 +7,7 @@ # 714. 买卖股票的最佳时机含手续费 -[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) +[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) 给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。 diff --git a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md index 4ab63e79..7734450e 100644 --- a/problems/0714.买卖股票的最佳时机含手续费(动态规划).md +++ b/problems/0714.买卖股票的最佳时机含手续费(动态规划).md @@ -6,7 +6,7 @@ ## 714.买卖股票的最佳时机含手续费 -[力扣题目链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) +[力扣题目链接](https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) 给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。 @@ -200,6 +200,29 @@ const maxProfit = (prices,fee) => { } ``` +TypeScript: + +```typescript +function maxProfit(prices: number[], fee: number): number { + /** + dp[i][0]:持有股票 + dp[i][1]: 不持有 + */ + const length: number = prices.length; + if (length === 0) return 0; + const dp: number[][] = new Array(length).fill(0).map(_ => []); + dp[0][0] = -prices[0]; + dp[0][1] = 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] - fee); + } + return dp[length - 1][1]; +}; +``` + + + -----------------------
diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index 87b1492a..18007b70 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -6,7 +6,7 @@ ## 718. 最长重复子数组 -[力扣题目链接](https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/) +[力扣题目链接](https://leetcode.cn/problems/maximum-length-of-repeated-subarray/) 给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。 @@ -297,6 +297,56 @@ const findLength = (nums1, nums2) => { } ``` +TypeScript: + +> 动态规划: + +```typescript +function findLength(nums1: number[], nums2: number[]): number { + /** + dp[i][j]:nums[i-1]和nums[j-1]结尾,最长重复子数组的长度 + */ + const length1: number = nums1.length, + length2: number = nums2.length; + const dp: number[][] = new Array(length1 + 1).fill(0) + .map(_ => new Array(length2 + 1).fill(0)); + let resMax: number = 0; + for (let i = 1; i <= length1; i++) { + for (let j = 1; j <= length2; j++) { + if (nums1[i - 1] === nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + resMax = Math.max(resMax, dp[i][j]); + } + } + } + return resMax; +}; +``` + +> 滚动数组: + +```typescript +function findLength(nums1: number[], nums2: number[]): number { + const length1: number = nums1.length, + length2: number = nums2.length; + const dp: number[] = new Array(length1 + 1).fill(0); + let resMax: number = 0; + for (let i = 1; i <= length1; i++) { + for (let j = length2; j >= 1; j--) { + if (nums1[i - 1] === nums2[j - 1]) { + dp[j] = dp[j - 1] + 1; + resMax = Math.max(resMax, dp[j]); + } else { + dp[j] = 0; + } + } + } + return resMax; +}; +``` + + + -----------------------
diff --git a/problems/0724.寻找数组的中心索引.md b/problems/0724.寻找数组的中心索引.md index 14dcd2c0..2fc42009 100644 --- a/problems/0724.寻找数组的中心索引.md +++ b/problems/0724.寻找数组的中心索引.md @@ -7,7 +7,7 @@ # 724.寻找数组的中心下标 -[力扣题目链接](https://leetcode-cn.com/problems/find-pivot-index/) +[力扣题目链接](https://leetcode.cn/problems/find-pivot-index/) 给你一个整数数组 nums ,请计算数组的 中心下标 。 diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index 4e4079a7..d2f041f5 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -6,7 +6,7 @@ # 738.单调递增的数字 -[力扣题目链接](https://leetcode-cn.com/problems/monotone-increasing-digits/) +[力扣题目链接](https://leetcode.cn/problems/monotone-increasing-digits/) 给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。 diff --git a/problems/0739.每日温度.md b/problems/0739.每日温度.md index 58edd489..4605de09 100644 --- a/problems/0739.每日温度.md +++ b/problems/0739.每日温度.md @@ -7,7 +7,7 @@ # 739. 每日温度 -[力扣题目链接](https://leetcode-cn.com/problems/daily-temperatures/) +[力扣题目链接](https://leetcode.cn/problems/daily-temperatures/) 请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。 @@ -34,7 +34,8 @@ 那么单调栈的原理是什么呢?为什么时间复杂度是O(n)就可以找到每一个元素的右边第一个比它大的元素位置呢? -单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素大的元素,优点是只需要遍历一次。 + +单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是只需要遍历一次。 在使用单调栈的时候首先要明确如下几点: @@ -192,7 +193,7 @@ class Solution { 否则的话,可以直接入栈。 注意,单调栈里 加入的元素是 下标。 */ - Stackstack=new Stack<>(); + Deque stack=new LinkedList<>(); stack.push(0); for(int i=1;istack=new Stack<>(); + Deque stack=new LinkedList<>(); for(int i=0;itemperatures[stack.peek()]){ @@ -371,6 +372,32 @@ var dailyTemperatures = function(temperatures) { }; ``` +TypeScript: + +> 精简版: + +```typescript +function dailyTemperatures(temperatures: number[]): number[] { + const length: number = temperatures.length; + const stack: number[] = []; + const resArr: number[] = new Array(length).fill(0); + stack.push(0); + for (let i = 1; i < length; i++) { + let top = stack[stack.length - 1]; + while ( + stack.length > 0 && + temperatures[top] < temperatures[i] + ) { + resArr[top] = i - top; + stack.pop(); + top = stack[stack.length - 1]; + } + stack.push(i); + } + return resArr; +}; +``` + diff --git a/problems/0746.使用最小花费爬楼梯.md b/problems/0746.使用最小花费爬楼梯.md index 5931fc8a..c2c73715 100644 --- a/problems/0746.使用最小花费爬楼梯.md +++ b/problems/0746.使用最小花费爬楼梯.md @@ -6,7 +6,7 @@ # 746. 使用最小花费爬楼梯 -[力扣题目链接](https://leetcode-cn.com/problems/min-cost-climbing-stairs/) +[力扣题目链接](https://leetcode.cn/problems/min-cost-climbing-stairs/) 数组的每个下标作为一个阶梯,第 i 个阶梯对应着一个非负数的体力花费值 cost[i](下标从 0 开始)。 diff --git a/problems/0763.划分字母区间.md b/problems/0763.划分字母区间.md index 2210cffa..eb21e42f 100644 --- a/problems/0763.划分字母区间.md +++ b/problems/0763.划分字母区间.md @@ -7,7 +7,7 @@ # 763.划分字母区间 -[力扣题目链接](https://leetcode-cn.com/problems/partition-labels/) +[力扣题目链接](https://leetcode.cn/problems/partition-labels/) 字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。 @@ -158,6 +158,71 @@ class Solution { return list; } } + +class Solution{ + /*解法二: 上述c++补充思路的Java代码实现*/ + + public int[][] findPartitions(String s) { + List temp = new ArrayList<>(); + int[][] hash = new int[26][2];//26个字母2列 表示该字母对应的区间 + + for (int i = 0; i < s.length(); i++) { + //更新字符c对应的位置i + char c = s.charAt(i); + if (hash[c - 'a'][0] == 0) hash[c - 'a'][0] = i; + + hash[c - 'a'][1] = i; + + //第一个元素区别对待一下 + hash[s.charAt(0) - 'a'][0] = 0; + } + + + List> h = new LinkedList<>(); + //组装区间 + for (int i = 0; i < 26; i++) { + //if (hash[i][0] != hash[i][1]) { + temp.clear(); + temp.add(hash[i][0]); + temp.add(hash[i][1]); + //System.out.println(temp); + h.add(new ArrayList<>(temp)); + // } + } + // System.out.println(h); + // System.out.println(h.size()); + int[][] res = new int[h.size()][2]; + for (int i = 0; i < h.size(); i++) { + List list = h.get(i); + res[i][0] = list.get(0); + res[i][1] = list.get(1); + } + + return res; + + } + + public List partitionLabels(String s) { + int[][] partitions = findPartitions(s); + List res = new ArrayList<>(); + Arrays.sort(partitions, (o1, o2) -> Integer.compare(o1[0], o2[0])); + int right = partitions[0][1]; + int left = 0; + for (int i = 0; i < partitions.length; i++) { + if (partitions[i][0] > right) { + //左边界大于右边界即可纪委一次分割 + res.add(right - left + 1); + left = partitions[i][0]; + } + right = Math.max(right, partitions[i][1]); + + } + //最右端 + res.add(right - left + 1); + return res; + + } +} ``` ### Python diff --git a/problems/0841.钥匙和房间.md b/problems/0841.钥匙和房间.md index 1cd13065..6f51b4ad 100644 --- a/problems/0841.钥匙和房间.md +++ b/problems/0841.钥匙和房间.md @@ -8,7 +8,7 @@ # 841.钥匙和房间 -[力扣题目链接](https://leetcode-cn.com/problems/keys-and-rooms/) +[力扣题目链接](https://leetcode.cn/problems/keys-and-rooms/) 有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index dccc5404..c0773653 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -7,7 +7,7 @@ # 844.比较含退格的字符串 -[力扣题目链接](https://leetcode-cn.com/problems/backspace-string-compare/) +[力扣题目链接](https://leetcode.cn/problems/backspace-string-compare/) 给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。 diff --git a/problems/0860.柠檬水找零.md b/problems/0860.柠檬水找零.md index aa09e1c6..f5785a91 100644 --- a/problems/0860.柠檬水找零.md +++ b/problems/0860.柠檬水找零.md @@ -7,7 +7,7 @@ # 860.柠檬水找零 -[力扣题目链接](https://leetcode-cn.com/problems/lemonade-change/) +[力扣题目链接](https://leetcode.cn/problems/lemonade-change/) 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index cb564fb6..8ca46db9 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -9,7 +9,7 @@ # 922. 按奇偶排序数组II -[力扣题目链接](https://leetcode-cn.com/problems/sort-array-by-parity-ii/) +[力扣题目链接](https://leetcode.cn/problems/sort-array-by-parity-ii/) 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 diff --git a/problems/0925.长按键入.md b/problems/0925.长按键入.md index 0ef5a3d7..bb6aeff2 100644 --- a/problems/0925.长按键入.md +++ b/problems/0925.长按键入.md @@ -6,7 +6,7 @@ # 925.长按键入 -[力扣题目链接](https://leetcode-cn.com/problems/long-pressed-name/) +[力扣题目链接](https://leetcode.cn/problems/long-pressed-name/) 你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 diff --git a/problems/0941.有效的山脉数组.md b/problems/0941.有效的山脉数组.md index 4b7a978c..310dd35a 100644 --- a/problems/0941.有效的山脉数组.md +++ b/problems/0941.有效的山脉数组.md @@ -7,7 +7,7 @@ # 941.有效的山脉数组 -[力扣题目链接](https://leetcode-cn.com/problems/valid-mountain-array/) +[力扣题目链接](https://leetcode.cn/problems/valid-mountain-array/) 给定一个整数数组 arr,如果它是有效的山脉数组就返回 true,否则返回 false。 @@ -157,6 +157,26 @@ var validMountainArray = function(arr) { }; ``` +## TypeScript + +```typescript +function validMountainArray(arr: number[]): boolean { + const length: number = arr.length; + if (length < 3) return false; + let left: number = 0, + right: number = length - 1; + while (left < (length - 1) && arr[left] < arr[left + 1]) { + left++; + } + while (right > 0 && arr[right] < arr[right - 1]) { + right--; + } + if (left === right && left !== 0 && right !== length - 1) + return true; + return false; +}; +``` + diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 9a510a1b..0aa04a02 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -7,7 +7,7 @@ # 968.监控二叉树 -[力扣题目链接](https://leetcode-cn.com/problems/binary-tree-cameras/) +[力扣题目链接](https://leetcode.cn/problems/binary-tree-cameras/) 给定一个二叉树,我们在树的节点上安装摄像头。 diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 0e79a3d6..4052c570 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -8,7 +8,7 @@ # 977.有序数组的平方 -[力扣题目链接](https://leetcode-cn.com/problems/squares-of-a-sorted-array/) +[力扣题目链接](https://leetcode.cn/problems/squares-of-a-sorted-array/) 给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。 @@ -23,6 +23,8 @@ # 思路 +为了易于大家理解,我还特意录制了视频,[本题视频讲解](https://www.bilibili.com/video/BV1QB4y1D7ep) + ## 暴力排序 最直观的想法,莫过于:每个数平方之后,排个序,美滋滋,代码如下: @@ -358,6 +360,30 @@ class Solution { } } ``` + +Kotlin: +```kotlin +class Solution { + // 双指针法 + fun sortedSquares(nums: IntArray): IntArray { + var res = IntArray(nums.size) + var left = 0 // 指向数组的最左端 + var right = nums.size - 1 // 指向数组端最右端 + // 选择平方数更大的那一个往 res 数组中倒序填充 + for (index in nums.size - 1 downTo 0) { + if (nums[left] * nums[left] > nums[right] * nums[right]) { + res[index] = nums[left] * nums[left] + left++ + } else { + res[index] = nums[right] * nums[right] + right-- + } + } + return res + } +} +``` + Scala: 双指针: diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index 36937b0b..6f54c098 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -8,7 +8,7 @@ # 1002. 查找常用字符 -[力扣题目链接](https://leetcode-cn.com/problems/find-common-characters/) +[力扣题目链接](https://leetcode.cn/problems/find-common-characters/) 给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符( 包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。 @@ -418,6 +418,38 @@ char ** commonChars(char ** words, int wordsSize, int* returnSize){ return ret; } ``` - +Scala: +```scala +object Solution { + def commonChars(words: Array[String]): List[String] = { + // 声明返回结果的不可变List集合,因为res要重新赋值,所以声明为var + var res = List[String]() + var hash = new Array[Int](26) // 统计字符出现的最小频率 + // 统计第一个字符串中字符出现的次数 + for (i <- 0 until words(0).length) { + hash(words(0)(i) - 'a') += 1 + } + // 统计其他字符串出现的频率 + for (i <- 1 until words.length) { + // 统计其他字符出现的频率 + var hashOtherStr = new Array[Int](26) + for (j <- 0 until words(i).length) { + hashOtherStr(words(i)(j) - 'a') += 1 + } + // 更新hash,取26个字母最小出现的频率 + for (k <- 0 until 26) { + hash(k) = math.min(hash(k), hashOtherStr(k)) + } + } + // 根据hash的结果转换输出的形式 + for (i <- 0 until 26) { + for (j <- 0 until hash(i)) { + res = res :+ (i + 'a').toChar.toString + } + } + res + } +} +``` -----------------------
diff --git a/problems/1005.K次取反后最大化的数组和.md b/problems/1005.K次取反后最大化的数组和.md index 202534da..8e161594 100644 --- a/problems/1005.K次取反后最大化的数组和.md +++ b/problems/1005.K次取反后最大化的数组和.md @@ -7,7 +7,7 @@ # 1005.K次取反后最大化的数组和 -[力扣题目链接](https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations/) +[力扣题目链接](https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/) 给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次。(我们可以多次选择同一个索引 i。) diff --git a/problems/1035.不相交的线.md b/problems/1035.不相交的线.md index 279ed816..83ccb08c 100644 --- a/problems/1035.不相交的线.md +++ b/problems/1035.不相交的线.md @@ -6,7 +6,7 @@ ## 1035.不相交的线 -[力扣题目链接](https://leetcode-cn.com/problems/uncrossed-lines/) +[力扣题目链接](https://leetcode.cn/problems/uncrossed-lines/) 我们在两条独立的水平线上按给定的顺序写下 A 和 B 中的整数。 @@ -183,6 +183,30 @@ const maxUncrossedLines = (nums1, nums2) => { }; ``` +TypeScript: + +```typescript +function maxUncrossedLines(nums1: number[], nums2: number[]): number { + /** + dp[i][j]: nums1前i-1个,nums2前j-1个,最大连线数 + */ + const length1: number = nums1.length, + length2: number = nums2.length; + const dp: number[][] = new Array(length1 + 1).fill(0) + .map(_ => new Array(length2 + 1).fill(0)); + for (let i = 1; i <= length1; i++) { + for (let j = 1; j <= length2; j++) { + if (nums1[i - 1] === nums2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[length1][length2]; +}; +``` + diff --git a/problems/1047.删除字符串中的所有相邻重复项.md b/problems/1047.删除字符串中的所有相邻重复项.md index 638c8f4e..7d160172 100644 --- a/problems/1047.删除字符串中的所有相邻重复项.md +++ b/problems/1047.删除字符串中的所有相邻重复项.md @@ -11,7 +11,7 @@ # 1047. 删除字符串中的所有相邻重复项 -[力扣题目链接](https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/) +[力扣题目链接](https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/) 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 @@ -374,6 +374,27 @@ func removeDuplicates(_ s: String) -> String { return String(stack) } ``` - +Scala: +```scala +object Solution { + import scala.collection.mutable + def removeDuplicates(s: String): String = { + var stack = mutable.Stack[Int]() + var str = "" // 保存最终结果 + for (i <- s.indices) { + var tmp = s(i) + // 如果栈非空并且栈顶元素等于当前字符,那么删掉栈顶和字符串最后一个元素 + if (!stack.isEmpty && tmp == stack.head) { + str = str.take(str.length - 1) + stack.pop() + } else { + stack.push(tmp) + str += tmp + } + } + str + } +} +``` -----------------------
diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index 3d256c3d..f4766069 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -7,7 +7,7 @@ ## 1049. 最后一块石头的重量 II -[力扣题目链接](https://leetcode-cn.com/problems/last-stone-weight-ii/) +[力扣题目链接](https://leetcode.cn/problems/last-stone-weight-ii/) 题目难度:中等 @@ -277,26 +277,29 @@ var lastStoneWeightII = function (stones) { }; ``` -TypeScript: -```typescript +TypeScript版本 + +```ts function lastStoneWeightII(stones: number[]): number { - const sum: number = stones.reduce((pre, cur) => pre + cur); - const bagSize: number = Math.floor(sum / 2); - const weightArr: number[] = stones; - const valueArr: number[] = stones; - const goodsNum: number = weightArr.length; - const dp: number[] = new Array(bagSize + 1).fill(0); - for (let i = 0; i < goodsNum; i++) { - for (let j = bagSize; j >= weightArr[i]; j--) { - dp[j] = Math.max(dp[j], dp[j - weightArr[i]] + valueArr[i]); + const sum: number = stones.reduce((a: number, b:number): number => a + b); + const target: number = Math.floor(sum / 2); + const n: number = stones.length; + // dp[j]表示容量(总数和)为j的背包所能装下的数(下标[0, i]之间任意取)的总和(<= 容量)的最大值 + const dp: number[] = new Array(target + 1).fill(0); + for (let i: number = 0; i < n; i++ ) { + for (let j: number = target; j >= stones[i]; j--) { + dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]); } } - return sum - dp[bagSize] * 2; + return sum - dp[target] - dp[target]; }; ``` + + + -----------------------
diff --git a/problems/1143.最长公共子序列.md b/problems/1143.最长公共子序列.md index ecedf89b..ad9825b8 100644 --- a/problems/1143.最长公共子序列.md +++ b/problems/1143.最长公共子序列.md @@ -6,7 +6,7 @@ ## 1143.最长公共子序列 -[力扣题目链接](https://leetcode-cn.com/problems/longest-common-subsequence/) +[力扣题目链接](https://leetcode.cn/problems/longest-common-subsequence/) 给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。 @@ -236,6 +236,32 @@ const longestCommonSubsequence = (text1, text2) => { }; ``` +TypeScript: + +```typescript +function longestCommonSubsequence(text1: string, text2: string): number { + /** + dp[i][j]: text1中前i-1个和text2中前j-1个,最长公共子序列的长度 + */ + const length1: number = text1.length, + length2: number = text2.length; + const dp: number[][] = new Array(length1 + 1).fill(0) + .map(_ => new Array(length2 + 1).fill(0)); + for (let i = 1; i <= length1; i++) { + for (let j = 1; j <= length2; j++) { + if (text1[i - 1] === text2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); + } + } + } + return dp[length1][length2]; +}; +``` + + + -----------------------
diff --git a/problems/1207.独一无二的出现次数.md b/problems/1207.独一无二的出现次数.md index ba92552a..5298f5be 100644 --- a/problems/1207.独一无二的出现次数.md +++ b/problems/1207.独一无二的出现次数.md @@ -6,7 +6,7 @@ # 1207.独一无二的出现次数 -[力扣题目链接](https://leetcode-cn.com/problems/unique-number-of-occurrences/) +[力扣题目链接](https://leetcode.cn/problems/unique-number-of-occurrences/) 给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。 @@ -150,5 +150,39 @@ var uniqueOccurrences = function(arr) { }; ``` +TypeScript: + +> 借用数组: + +```typescript +function uniqueOccurrences(arr: number[]): boolean { + const countArr: number[] = new Array(2001).fill(0); + for (let i = 0, length = arr.length; i < length; i++) { + countArr[arr[i] + 1000]++; + } + const flagArr: boolean[] = new Array(1001).fill(false); + for (let count of countArr) { + if (count === 0) continue; + if (flagArr[count] === true) return false; + flagArr[count] = true; + } + return true; +}; +``` + +> 借用map、set + +```typescript +function uniqueOccurrences(arr: number[]): boolean { + const countMap: Map = new Map(); + arr.forEach(val => { + countMap.set(val, (countMap.get(val) || 0) + 1); + }) + return countMap.size === new Set(countMap.values()).size; +}; +``` + + + -----------------------
diff --git a/problems/1221.分割平衡字符串.md b/problems/1221.分割平衡字符串.md index 1a9b34a2..08d4fee7 100644 --- a/problems/1221.分割平衡字符串.md +++ b/problems/1221.分割平衡字符串.md @@ -6,7 +6,7 @@ # 1221. 分割平衡字符串 -[力扣题目链接](https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/) +[力扣题目链接](https://leetcode.cn/problems/split-a-string-in-balanced-strings/) 在一个 平衡字符串 中,'L' 和 'R' 字符的数量是相同的。 diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index 838c3a96..5ca73607 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -8,9 +8,9 @@ # 1356. 根据数字二进制下 1 的数目排序 -[力扣题目链接](https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/) +[力扣题目链接](https://leetcode.cn/problems/sort-integers-by-the-number-of-1-bits/) -题目链接:https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/ +题目链接:https://leetcode.cn/problems/sort-integers-by-the-number-of-1-bits/ 给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。 diff --git a/problems/1365.有多少小于当前数字的数字.md b/problems/1365.有多少小于当前数字的数字.md index 78fa84c0..3aaadf6d 100644 --- a/problems/1365.有多少小于当前数字的数字.md +++ b/problems/1365.有多少小于当前数字的数字.md @@ -8,7 +8,7 @@ # 1365.有多少小于当前数字的数字 -[力扣题目链接](https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/) +[力扣题目链接](https://leetcode.cn/problems/how-many-numbers-are-smaller-than-the-current-number/) 给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。 @@ -217,6 +217,46 @@ var smallerNumbersThanCurrent = function(nums) { }; ``` +TypeScript: + +> 暴力法: + +```typescript +function smallerNumbersThanCurrent(nums: number[]): number[] { + const length: number = nums.length; + const resArr: number[] = []; + for (let i = 0; i < length; i++) { + let count: number = 0; + for (let j = 0; j < length; j++) { + if (nums[j] < nums[i]) { + count++; + } + } + resArr[i] = count; + } + return resArr; +}; +``` + +> 排序+hash + +```typescript +function smallerNumbersThanCurrent(nums: number[]): number[] { + const length: number = nums.length; + const sortedArr: number[] = [...nums]; + sortedArr.sort((a, b) => a - b); + const hashMap: Map = new Map(); + for (let i = length - 1; i >= 0; i--) { + hashMap.set(sortedArr[i], i); + } + const resArr: number[] = []; + for (let i = 0; i < length; i++) { + resArr[i] = hashMap.get(nums[i]); + } + return resArr; +}; +``` + ----------------------- diff --git a/problems/1382.将二叉搜索树变平衡.md b/problems/1382.将二叉搜索树变平衡.md index 57231ec4..d944ac30 100644 --- a/problems/1382.将二叉搜索树变平衡.md +++ b/problems/1382.将二叉搜索树变平衡.md @@ -7,7 +7,7 @@ # 1382.将二叉搜索树变平衡 -[力扣题目链接](https://leetcode-cn.com/problems/balance-a-binary-search-tree/) +[力扣题目链接](https://leetcode.cn/problems/balance-a-binary-search-tree/) 给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。 diff --git a/problems/qita/gitserver.md b/problems/qita/gitserver.md new file mode 100644 index 00000000..9ee06ae4 --- /dev/null +++ b/problems/qita/gitserver.md @@ -0,0 +1,312 @@ + +# 一文手把手教你搭建Git私服 + +## 为什么要搭建Git私服 + +很多同学都问文章,文档,资料怎么备份啊,自己电脑和公司电脑怎么随时同步资料啊等等,这里呢我写一个搭建自己的git私服的详细教程 + +为什么要搭建一个Git私服呢,而不是用Github免费的私有仓库,有以下几点: +* Github 私有仓库真的慢,文件一旦多了,或者有图片文件,git pull 的时候半天拉不下来 +* 自己的文档难免有自己个人信息,放在github心里也是担心的 +* 想建几个库就建几个,想几个人合作开发都可以,不香么? + +**网上可以搜到很多git搭建,但是说的模棱两可**,而且有的直接是在本地搭建git服务,既然是备份,搭建在本地哪有备份的意义,一定要有一个远端服务器, 而且自己的电脑和公司的电脑还是同步自己的文章,文档和资料等等。 + + +适合人群: 想通过git私服来备份自己的文章,Markdown,并做版本管理的同学 +最后,写好每篇 Chat 是对我的责任,也是对你的尊重。谢谢大家~ + +正文如下: + +----------------------------- + +## 如何找到可以外网访问服务器 + +有的同学问了,自己的电脑就不能作为服务器么? + +这里要说一下,安装家庭带宽,运营商默认是不会给我们独立分配公网IP的 + +一般情况下是一片区域公用一个公网IP池,所以外网是不能访问到在家里我们使用的电脑的 + +除非我们自己去做映射,这其实非常麻烦而且公网IP池 是不断变化的 + +辛辛苦苦做了映射,运营商给IP一换,我们的努力就白扯了 + +那我们如何才能找到一个外网可以访问的服务器呢,此时云计算拯救了我们。 + +推荐大家选一家云厂商(阿里云,腾讯云,百度云都可以)在上面上买一台云服务器 + +* [阿里云活动期间服务器购买](https://www.aliyun.com/minisite/goods?taskCode=shareNew2205&recordId=3641992&userCode=roof0wob) +* [腾讯云活动期间服务器购买](https://curl.qcloud.com/EiaMXllu) + +云厂商经常做活动,如果从来没有买过云服务器的账号更便宜,低配一年一百块左右的样子,强烈推荐一起买个三年。 + +买云服务器的时候推荐直接安装centos系统。 + +这里要说一下,有了自己的云服务器之后 不仅仅可以用来做git私服 + +**同时还可以做网站,做程序后台,跑程序,做测试**(这样我们自己的电脑就不会因为自己各种搭建环境下载各种包而搞的的烂糟糟),等等等。 + +有自己云服务器和一个公网IP真的是一件非常非常幸福的事情,能体验到自己的服务随时可以部署上去提供给所有人使用的喜悦。 + +外网可以访问的服务器解决了,接下来就要部署git服务了 + +本文将采用centos系统来部署git私服 + +## 服务器端安装Git + +切换至root账户 + +``` +su root +``` + +看一下服务器有没有安装git,如果出现下面信息就说明是有git的 +``` +[root@instance-5fcyjde7 ~]# git +usage: git [--version] [--help] [-c name=value] + [--exec-path[=]] [--html-path] [--man-path] [--info-path] + [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] + [--git-dir=] [--work-tree=] [--namespace=] + [] + +The most commonly used git commands are: + add Add file contents to the index + bisect Find by binary search the change that introduced a bug + branch List, create, or delete branches + checkout Checkout a branch or paths to the working tree + clone Clone a repository into a new directory + commit Record changes to the repository + diff Show changes between commits, commit and working tree, etc + fetch Download objects and refs from another repository + grep Print lines matching a pattern + init Create an empty Git repository or reinitialize an existing one + log Show commit logs + merge Join two or more development histories together + mv Move or rename a file, a directory, or a symlink + pull Fetch from and merge with another repository or a local branch + push Update remote refs along with associated objects + rebase Forward-port local commits to the updated upstream head + reset Reset current HEAD to the specified state + rm Remove files from the working tree and from the index + show Show various types of objects + status Show the working tree status + tag Create, list, delete or verify a tag object signed with GPG + +'git help -a' and 'git help -g' lists available subcommands and some +concept guides. See 'git help ' or 'git help ' +to read about a specific subcommand or concept. +``` + +如果没有git,就安装一下,yum安装的版本默认是 `1.8.3.1` + +``` +yum install git +``` + +安装成功之后,看一下自己安装的版本 + +``` +git --version +``` + +## 服务器端设置Git账户 + +创建一个git的linux账户,这个账户只做git私服的操作,也是为了安全起见 + +如果不新创建一个linux账户,在自己的常用的linux账户下创建的话,哪天手抖 来一个`rm -rf *` 操作 数据可全没了 + +**这里linux git账户的密码设置的尽量复杂一些,我这里为了演示,就设置成为'gitpassword'** +``` +adduser git +passwd gitpassword +``` + +然后就要切换成git账户,进行后面的操作了 +``` +[root@instance-5fcyjde7 ~]# su - git +``` + +看一下自己所在的目录,是不是在git目录下面 + +``` +[git@instance-5fcyjde7 ~]$ pwd +/home/git +``` + +## 服务器端密钥管理 + +创建`.ssh` 目录,如果`.ssh` 已经存在了,可以忽略这一项 + +为啥用配置ssh公钥呢,同学们记不记得我急使用github上传上传代码的时候也要把自己的公钥配置上github上 + +这也是方面每次操作git仓库的时候不用再去输入密码 + +``` +cd ~/ +mkdir .ssh +``` + +进入.ssh 文件下,创建一个 `authorized_keys` 文件,这个文件就是后面就是要放我们客户端的公钥 + +``` +cd ~/.ssh +touch authorized_keys +``` + +别忘了`authorized_keys`给设置权限,很多同学发现自己不能免密登陆,都是因为忘记了给`authorized_keys` 设置权限 + +``` +chmod 700 /home/git/.ssh +chmod 600 /home/git/.ssh/authorized_keys +``` + +接下来我们要把客户端的公钥放在git服务器上,我们在回到客户端,创建一个公钥 + +在我们自己的电脑上,有公钥和私钥 两个文件分别是:`id_rsa` 和 `id_rsa.pub` + +如果是`windows`系统公钥私钥的目录在`C:\Users\用户名\.ssh` 下 + +如果是mac 或者 linux, 公钥和私钥的目录这里 `cd ~/.ssh/`, 如果发现自己的电脑上没有公钥私钥,那就自己创建一个 + +创建密钥的命令 + +``` +ssh-keygen -t rsa +``` + +创建密钥的过程中,一路点击回车就可以了。不需要填任何东西 + +把公钥拷贝到git服务器上,将我们刚刚生成的`id_rsa.pub`,拷贝到git服务器的`/home/git/.ssh/`目录 + +在git服务器上,将公钥添加到`authorized_keys` 文件中 + +``` +cd /home/git/.ssh/ +cat id_rsa.pub >> authorized_keys +``` + +如何看我们配置的密钥是否成功呢, 在客户点直接登录git服务器,看看是否是免密登陆 +``` +ssh git@git服务器ip +``` + +例如: + +``` +ssh git@127.0.0.1 +``` + +如果可以免密登录,那就说明服务器端密钥配置成功了 + +## 服务器端部署Git 仓库 + +我们在登陆到git 服务器端,切换为成 git账户 + +如果是root账户切换成git账户 +``` +su - git +``` + +如果是其他账户切换为git账户 +``` +sudo su - git +``` + +进入git目录下 +``` +cd ~/git +``` + +创建我们的第一个Git私服的仓库,我们叫它为world仓库 + +那么首先创建一个文件夹名为: world.git ,然后进入这个目录 + +有同学问,为什么文件夹名字后面要放`.git`, 其实不这样命名也是可以的 + +但是细心的同学可能注意到,我们平时在github上 `git clone` 其他人的仓库的时候,仓库名字后面,都是加上`.git`的 + +例如下面这个例子,其实就是github对仓库名称的一个命名规则,所以我们也遵守github的命名规则。 + +``` +git clone https://github.com/youngyangyang04/NoSQLAttack.git +``` + +所以我们的操作是 +``` +[git@localhost git]# mkdir world.git +[git@localhost git]# cd world.git +``` + +初始化我们的`world`仓库 + +``` +git init --bare + +``` + +**如果我们想创建多个仓库,就在这里创建多个文件夹并初始化就可以了,和world仓库的操作过程是一样一样的** + +现在我们服务端的git仓库就部署完了,接下来就看看客户端,如何使用这个仓库呢 + +## 客户端连接远程仓库 + +我们在自己的电脑上创建一个文件夹 也叫做`world`吧 + +其实这里命名是随意的,但是我们为了和git服务端的仓库名称保持同步。 这样更直观我们操作的是哪一个仓库。 + +``` +mkdir world +cd world +``` + +进入world文件,并初始化操作 + +``` +cd world +git init +``` + +在world目录上创建一个测试文件,并且将其添加到git版本管理中 + +``` +touch test +git add test +git commit -m "add test file" +``` + +将次仓库和远端仓库同步 + +``` +git remote add origin git@git服务器端的ip:world.git +git push -u origin master +``` + +此时这个test测试文件就已经提交到我们的git远端私服上了 + +## Git私服安全问题 + +这里有两点安全问题 + +### linux git的密码不要泄露出去 + +否则,别人可以通过 ssh git@git服务器IP 来登陆到你的git私服服务器上 + +当然了,这里同学们如果买的是云厂商的云服务器的话 + +如果有人恶意想通过 尝试不同密码链接的方式来链接你的服务器,重试三次以上 + +这个客户端的IP就会被封掉,同时邮件通知我们可以IP来自哪里 + +所以大可放心 密码只要我们不泄露出去,基本上不会有人同时不断尝试密码的方式来登上我们的git私服服务器 + +### 私钥文件`id_rsa` 不要给别人 + +如果有人得到了这个私钥,就可以免密码登陆我们的git私服上了,我相信大家也不至于把自己的私钥主动给别人吧 + +## 总结 + +这里就是整个git私服搭建的全过程,安全问题我也给大家列举了出来,接下来好好享受自己的Git私服吧 + +**enjoy!** + diff --git a/problems/qita/server.md b/problems/qita/server.md new file mode 100644 index 00000000..1d7a1d6b --- /dev/null +++ b/problems/qita/server.md @@ -0,0 +1,129 @@ + +# 一台服务器有什么用! + +* [阿里云活动期间服务器购买](https://www.aliyun.com/minisite/goods?taskCode=shareNew2205&recordId=3641992&userCode=roof0wob) +* [腾讯云活动期间服务器购买](https://curl.qcloud.com/EiaMXllu) + +但在组织这场活动的时候,了解到大家都有一个共同的问题: **这个服务器究竟有啥用??** + +这真是一个好问题,而且我一句两句还说不清楚,所以就专门发文来讲一讲。 + +同时我还录制的一期视频,哈哈我的视频号,大家可以关注一波。 + + +一说到服务器,可能很多人都说搞分布式,做计算,搞爬虫,做程序后台服务,多人合作等等。 + +其实这些普通人都用不上,我来说一说大家能用上的吧。 + +## 搭建git私服 + +大家平时工作的时候一定有一个自己的工作文件夹,学生的话就是自己的课件,考试,准备面试的资料等等。 + +已经工作的录友,会有一个文件夹放着自己重要的文档,Markdown,图片,简历等等。 + +这么重要的文件夹,而且我们每天都要更新,也担心哪天电脑丢了,或者坏了,突然这些都不见了。 + +所以我们想备份嘛。 + +还有就是我们经常个人电脑和工作电脑要同步一些私人资料,而不是用微信传来传去。 + +这些都是git私服的使用场景,而且很好用。 + +大家也知道 github,gitee也可以搞私人仓库 用来备份,同步文件,但自己的文档可能放着很多重要的信息,包括自己的各种密码,密钥之类的,放到上面未必安全。你就不怕哪些重大bug把你的信息都泄漏了么[机智] + +更关键的是,github 和 gitee都限速的。毕竟人家的功能定位并不是网盘。 + +项目里有大文件(几百M以上),例如pdf,ppt等等 其上传和下载速度会让你窒息。 + +**后面我会发文专门来讲一讲,如何大家git私服!** + +## 搞一个文件存储 + +这个可以用来生成文件的下载链接,也可以把本地文件传到服务器上。 + +相当于自己做一个对象存储,其实云厂商也有对象存储的产品。 + +不过我们自己也可以做一个,不够很多很同学应该都不知道对象存储怎么用吧,其实我们用服务器可以自己做一个类似的公司。 + +我现在就用自己用go写的一个工具,部署在服务器上。 用来和服务器传文件,或者生成一些文件的临时下载链接。 + +这些都是直接命令行操作的, + +操作方式这样,我把命令包 包装成一个shell命令,想传那个文件,直接 uploadtomyserver,然后就返回可以下载的链接,这个文件也同时传到了我的服务器上。 + +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211126165643.png) + +我也把我的项目代码放在了github上: + +https://github.com/youngyangyang04/fileHttpServer + +感兴趣的录友可以去学习一波,顺便给个star 哈哈 + + +## 网站 + +做网站,例如 大家知道用html 写几行代码,就可以生成一个网页,但怎么给别人展示呢? + +大家如果用自己的电脑做服务器,只能同一个路由器下的设备可以访问你的网站,可能这个设备出了这个屋子 都访问不了你的网站了。 + +因为你的IP不是公网IP。 + +如果有了一台云服务器,都是配公网IP,你的网站就可以让任何人访问了。 + +或者说 你提供的一个服务就可以让任何人使用。 + +例如第二个例子中,我们可以自己开发一个文件存储,这个服务,我只把把命令行给其他人,其他人都可以使用我的服务来生成链接,当然他们的文件也都传到了我的服务器上。 + +再说一个使用场景。 + +我之前在组织免费里服务器的活动的时候,阿里云给我一个excel,让面就是从我这里买服务器录友的名单,我直接把这个名单甩到群里,让大家自己检查,出现在名单里就可以找我返现,这样做是不是也可以。 + +这么做有几个很大的问题: +* 大家都要去下载excel,做对比,会有人改excel的内容然后就说是从你这里买的,我不可能挨个去比较excel有没有改动 +* excel有其他人的个人信息,这是不能暴漏的。 +* 如果每个人自己用excel查询,私信我返现,一个将近两千人找我返现,我微信根本处理不过来,这就变成体力活了。 + +那应该怎么做呢, + +我就简单写一个查询的页面,后端逻辑就是读一个execel表格,大家在查询页面输入自己的阿里云ID,如果在excel里,页面就会返回返现群的二维码,大家就可以自主扫码加群了。 + +这样,我最后就直接在返现群里 发等额红包就好了,是不是极大降低人力成本了 + +当然我是把 17个返现群的二维码都生成好了,按照一定的规则,展现给查询通过的录友。 + +就是这样一个非常普通的查询页面。 + +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211126160200.png) + +查询通过之后,就会展现返现群二维码。 + +![](https://code-thinking-1253855093.file.myqcloud.com/pics/20211127160558.png) + +但要部署在服务器上,因为没有公网IP,别人用不了你的服务。 + + +## 学习linux + +学习linux其实在自己的电脑上搞一台虚拟机,或者安装双系统也可以学习,不过这很考验你的电脑性能如何了。 + +如果你有一个服务器,那就是独立的一台电脑,你怎么霍霍就怎么霍霍,而且一年都不用关机的,可以一直跑你的任务,和你本地电脑也完全隔离。 + +更方便的是,你目前系统假如是centos,想做一个实验需要在unbantu上,如果是云服务器,更换系统就是在 后台点一下,一键重装,云厂商基本都是支持所有系统一件安装的。 + +我们平时自己玩linux经常是配各种环境,然后这个linux就被自己玩坏了(一般都是毫无节制使用root权限导致的),总之就是环境配不起来了,基本就要重装了。 + +那云服务器重装系统可太方便了。 + +还有就是加入你好不容易配好的环境,如果以后把这个环境玩坏了,你先回退这之前配好的环境而不是重装系统在重新配一遍吧。 + +那么可以用云服务器的镜像保存功能,就是你配好环境的那一刻就可以打一个镜像包,以后如果环境坏了,直接回退到上次镜像包的状态,这是不是就很香了。 + + +## 总结 + +其实云服务器还有很多其他用处,不过我就说一说大家普遍能用的上的。 + + +* [阿里云活动期间服务器购买](https://www.aliyun.com/minisite/goods?taskCode=shareNew2205&recordId=3641992&userCode=roof0wob) +* [腾讯云活动期间服务器购买](https://curl.qcloud.com/EiaMXllu) + diff --git a/problems/其他/参与本项目.md b/problems/qita/参与本项目.md similarity index 100% rename from problems/其他/参与本项目.md rename to problems/qita/参与本项目.md diff --git a/problems/二叉树理论基础.md b/problems/二叉树理论基础.md index 9c151e32..9e10ac20 100644 --- a/problems/二叉树理论基础.md +++ b/problems/二叉树理论基础.md @@ -258,6 +258,13 @@ class TreeNode { } } ``` - +Scala: +```scala +class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) { + var value: Int = _value + var left: TreeNode = _left + var right: TreeNode = _right +} +``` -----------------------
diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index f6edf586..9ca6ac39 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -591,6 +591,80 @@ function postorderTraversal(root: TreeNode | null): number[] { return res; }; ``` +Scala: +```scala +// 前序遍历 +object Solution { + import scala.collection.mutable + def preorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + val stack = mutable.Stack[TreeNode]() + if (root != null) stack.push(root) + while (!stack.isEmpty) { + var curNode = stack.top + if (curNode != null) { + stack.pop() + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + stack.push(curNode) + stack.push(null) + } else { + stack.pop() + res.append(stack.pop().value) + } + } + res.toList + } +} +// 中序遍历 +object Solution { + import scala.collection.mutable + def inorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + val stack = mutable.Stack[TreeNode]() + if (root != null) stack.push(root) + while (!stack.isEmpty) { + var curNode = stack.top + if (curNode != null) { + stack.pop() + if (curNode.right != null) stack.push(curNode.right) + stack.push(curNode) + stack.push(null) + if (curNode.left != null) stack.push(curNode.left) + } else { + // 等于空的时候好办,弹出这个元素 + stack.pop() + res.append(stack.pop().value) + } + } + res.toList + } +} + +// 后序遍历 +object Solution { + import scala.collection.mutable + def postorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + val stack = mutable.Stack[TreeNode]() + if (root != null) stack.push(root) + while (!stack.isEmpty) { + var curNode = stack.top + if (curNode != null) { + stack.pop() + stack.push(curNode) + stack.push(null) + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + } else { + stack.pop() + res.append(stack.pop().value) + } + } + res.toList + } +} +``` -----------------------
diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 13ba5f1e..dc8e812c 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -11,9 +11,9 @@ 看完本篇大家可以使用迭代法,再重新解决如下三道leetcode上的题目: -* [144.二叉树的前序遍历](https://leetcode-cn.com/problems/binary-tree-preorder-traversal/) -* [94.二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/) -* [145.二叉树的后序遍历](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/) +* [144.二叉树的前序遍历](https://leetcode.cn/problems/binary-tree-preorder-traversal/) +* [94.二叉树的中序遍历](https://leetcode.cn/problems/binary-tree-inorder-traversal/) +* [145.二叉树的后序遍历](https://leetcode.cn/problems/binary-tree-postorder-traversal/) 为什么可以用迭代法(非递归的方式)来实现二叉树的前后中序遍历呢? @@ -568,6 +568,71 @@ func inorderTraversal(_ root: TreeNode?) -> [Int] { return result } ``` +Scala: +```scala +// 前序遍历(迭代法) +object Solution { + import scala.collection.mutable + def preorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + if (root == null) return res.toList + // 声明一个栈,泛型为TreeNode + val stack = mutable.Stack[TreeNode]() + stack.push(root) // 先把根节点压入栈 + while (!stack.isEmpty) { + var curNode = stack.pop() + res.append(curNode.value) // 先把这个值压入栈 + // 如果当前节点的左右节点不为空,则入栈,先放右节点,再放左节点 + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + } + res.toList + } +} +// 中序遍历(迭代法) +object Solution { + import scala.collection.mutable + def inorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ArrayBuffer[Int]() + if (root == null) return res.toList + val stack = mutable.Stack[TreeNode]() + var curNode = root + // 将左节点都入栈,当遍历到最左(到空)的时候,再弹出栈顶元素,加入res + // 再把栈顶元素的右节点加进来,继续下一轮遍历 + while (curNode != null || !stack.isEmpty) { + if (curNode != null) { + stack.push(curNode) + curNode = curNode.left + } else { + curNode = stack.pop() + res.append(curNode.value) + curNode = curNode.right + } + } + res.toList + } +} + +// 后序遍历(迭代法) +object Solution { + import scala.collection.mutable + def postorderTraversal(root: TreeNode): List[Int] = { + val res = mutable.ListBuffer[Int]() + if (root == null) return res.toList + val stack = mutable.Stack[TreeNode]() + stack.push(root) + while (!stack.isEmpty) { + val curNode = stack.pop() + res.append(curNode.value) + // 这次左节点先入栈,右节点再入栈 + if(curNode.left != null) stack.push(curNode.left) + if(curNode.right != null) stack.push(curNode.right) + } + // 最后需要翻转List + res.reverse.toList + } +} +``` -----------------------
diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index 186c39d3..1cce2a0d 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -99,9 +99,9 @@ void traversal(TreeNode* cur, vector& vec) { 此时大家可以做一做leetcode上三道题目,分别是: -* [144.二叉树的前序遍历](https://leetcode-cn.com/problems/binary-tree-preorder-traversal/) -* [145.二叉树的后序遍历](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/) -* [94.二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/) +* [144.二叉树的前序遍历](https://leetcode.cn/problems/binary-tree-preorder-traversal/) +* [145.二叉树的后序遍历](https://leetcode.cn/problems/binary-tree-postorder-traversal/) +* [94.二叉树的中序遍历](https://leetcode.cn/problems/binary-tree-inorder-traversal/) 可能有同学感觉前后中序遍历的递归太简单了,要打迭代法(非递归),别急,我们明天打迭代法,打个通透! @@ -470,5 +470,56 @@ func postorder(_ root: TreeNode?, res: inout [Int]) { res.append(root!.val) } ``` +Scala: 前序遍历:(144.二叉树的前序遍历) +```scala +object Solution { + import scala.collection.mutable.ListBuffer + def preorderTraversal(root: TreeNode): List[Int] = { + val res = ListBuffer[Int]() + def traversal(curNode: TreeNode): Unit = { + if(curNode == null) return + res.append(curNode.value) + traversal(curNode.left) + traversal(curNode.right) + } + traversal(root) + res.toList + } +} +``` +中序遍历:(94. 二叉树的中序遍历) +```scala +object Solution { + import scala.collection.mutable.ListBuffer + def inorderTraversal(root: TreeNode): List[Int] = { + val res = ListBuffer[Int]() + def traversal(curNode: TreeNode): Unit = { + if(curNode == null) return + traversal(curNode.left) + res.append(curNode.value) + traversal(curNode.right) + } + traversal(root) + res.toList + } +} +``` +后序遍历:(145. 二叉树的后序遍历) +```scala +object Solution { + import scala.collection.mutable.ListBuffer + def postorderTraversal(root: TreeNode): List[Int] = { + val res = ListBuffer[Int]() + def traversal(curNode: TreeNode): Unit = { + if (curNode == null) return + traversal(curNode.left) + traversal(curNode.right) + res.append(curNode.value) + } + traversal(root) + res.toList + } +} +``` -----------------------
diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 037bd427..78b03b17 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -7,7 +7,7 @@ # 题目:剑指Offer 05.替换空格 -[力扣题目链接](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/) +[力扣题目链接](https://leetcode.cn/problems/ti-huan-kong-ge-lcof/) 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 @@ -413,8 +413,98 @@ func replaceSpace(_ s: String) -> String { } ``` +Scala: + +方式一: 双指针 +```scala +object Solution { + def replaceSpace(s: String): String = { + var count = 0 + s.foreach(c => if (c == ' ') count += 1) // 统计空格的数量 + val sOldSize = s.length // 旧数组字符串长度 + val sNewSize = s.length + count * 2 // 新数组字符串长度 + val res = new Array[Char](sNewSize) // 新数组 + var index = sNewSize - 1 // 新数组索引 + // 逆序遍历 + for (i <- (0 until sOldSize).reverse) { + if (s(i) == ' ') { + res(index) = '0' + index -= 1 + res(index) = '2' + index -= 1 + res(index) = '%' + } else { + res(index) = s(i) + } + index -= 1 + } + res.mkString + } +} +``` +方式二: 使用一个集合,遇到空格就添加%20 +```scala +object Solution { + import scala.collection.mutable.ListBuffer + def replaceSpace(s: String): String = { + val res: ListBuffer[Char] = ListBuffer[Char]() + for (i <- s.indices) { + if (s(i) == ' ') { + res += '%' + res += '2' + res += '0' + }else{ + res += s(i) + } + } + res.mkString + } +} +``` +方式三: 使用map +```scala +object Solution { + def replaceSpace(s: String): String = { + s.map(c => if(c == ' ') "%20" else c).mkString + } + } +``` +PHP: +```php +function replaceSpace($s){ + $sLen = strlen($s); + $moreLen = $this->spaceLen($s) * 2; + + $head = $sLen - 1; + $tail = $sLen + $moreLen - 1; + + $s = $s . str_repeat(' ', $moreLen); + while ($head != $tail) { + if ($s[$head] == ' ') { + $s[$tail--] = '0'; + $s[$tail--] = '2'; + $s[$tail] = '%'; + } else { + $s[$tail] = $s[$head]; + } + $head--; + $tail--; + } + return $s; +} +// 统计空格个数 +function spaceLen($s){ + $count = 0; + for ($i = 0; $i < strlen($s); $i++) { + if ($s[$i] == ' ') { + $count++; + } + } + return $count; +} +``` ----------------------- diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index fec83e1d..4674c141 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -9,7 +9,7 @@ # 题目:剑指Offer58-II.左旋转字符串 -[力扣题目链接](https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/) +[力扣题目链接](https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/) 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。 @@ -291,6 +291,56 @@ func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) { ``` +### PHP + +```php +function reverseLeftWords($s, $n) { + $this->reverse($s,0,$n-1); //反转区间为前n的子串 + $this->reverse($s,$n,strlen($s)-1); //反转区间为n到末尾的子串 + $this->reverse($s,0,strlen($s)-1); //反转整个字符串 + return $s; +} + +// 按指定进行翻转 【array、string都可】 +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 reverseLeftWords(s: String, n: Int): String = { + var str = s.toCharArray // 转换为Array + // abcdefg => ba cdefg + reverseString(str, 0, n - 1) + // ba cdefg => ba gfedc + reverseString(str, n, str.length - 1) + // ba gfedc => cdefgab + reverseString(str, 0, str.length - 1) + // 最终返回,return关键字可以省略 + new String(str) + } + // 翻转字符串 + 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 + } + } +} +``` + diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index f48097e1..cbfe046a 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -365,6 +365,84 @@ class Solution: return res ``` +JavaScript: + +**90.子集II** + +```javascript +function subsetsWithDup(nums) { + nums.sort((a, b) => a - b); + const resArr = []; + backTraking(nums, 0, []); + return resArr; + function backTraking(nums, startIndex, route) { + resArr.push([...route]); + const helperSet = new Set(); + for (let i = startIndex, length = nums.length; i < length; i++) { + if (helperSet.has(nums[i])) continue; + helperSet.add(nums[i]); + route.push(nums[i]); + backTraking(nums, i + 1, route); + route.pop(); + } + } +}; +``` + +**40. 组合总和 II** + +```javascript +function combinationSum2(candidates, target) { + candidates.sort((a, b) => a - b); + const resArr = []; + backTracking(candidates, target, 0, 0, []); + return resArr; + function backTracking( candidates, target, curSum, startIndex, route ) { + if (curSum > target) return; + if (curSum === target) { + resArr.push([...route]); + return; + } + const helperSet = new Set(); + for (let i = startIndex, length = candidates.length; i < length; i++) { + let tempVal = candidates[i]; + if (helperSet.has(tempVal)) continue; + helperSet.add(tempVal); + route.push(tempVal); + backTracking(candidates, target, curSum + tempVal, i + 1, route); + route.pop(); + } + } +}; +``` + +**47. 全排列 II** + +```javaescript +function permuteUnique(nums) { + const resArr = []; + const usedArr = []; + backTracking(nums, []); + return resArr; + function backTracking(nums, route) { + if (nums.length === route.length) { + resArr.push([...route]); + return; + } + const usedSet = new Set(); + for (let i = 0, length = nums.length; i < length; i++) { + if (usedArr[i] === true || usedSet.has(nums[i])) continue; + usedSet.add(nums[i]); + route.push(nums[i]); + usedArr[i] = true; + backTracking(nums, route); + usedArr[i] = false; + route.pop(); + } + } +}; +``` + TypeScript: **90.子集II** @@ -376,7 +454,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]); const helperSet: Set = new Set(); for (let i = startIndex, length = nums.length; i < length; i++) { if (helperSet.has(nums[i])) continue; @@ -403,7 +481,7 @@ function combinationSum2(candidates: number[], target: number): number[][] { ) { if (curSum > target) return; if (curSum === target) { - resArr.push(route.slice()); + resArr.push([...route]); return; } const helperSet: Set = new Set(); @@ -430,7 +508,7 @@ function permuteUnique(nums: number[]): number[][] { return resArr; function backTracking(nums: number[], route: number[]): void { if (nums.length === route.length) { - resArr.push(route.slice()); + resArr.push([...route]); return; } const usedSet: Set = new Set(); diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index d2ab191a..a40a92ab 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -380,53 +380,31 @@ func main() { ### javascript ```js -/** - * - * @param {Number []} weight - * @param {Number []} value - * @param {Number} size - * @returns - */ +function testWeightBagProblem (weight, value, size) { + // 定义 dp 数组 + const len = weight.length, + dp = Array(len).fill().map(() => Array(size + 1).fill(0)); -function testWeightBagProblem(weight, value, size) { -const len = weight.length, -dp = Array.from({length: len}).map( -() => Array(size + 1)) //JavaScript 数组是引用类型 -for(let i = 0; i < len; i++) { //初始化最左一列,即背包容量为0时的情况 -dp[i][0] = 0; -} -for(let j = 1; j < size+1; j++) { //初始化第0行, 只有一件物品的情况 -if(weight[0] <= j) { -dp[0][j] = value[0]; -} else { -dp[0][j] = 0; -} -} - -for(let i = 1; i < len; i++) { //dp[i][j]由其左上方元素推导得出 -for(let j = 1; j < size+1; j++) { -if(j < weight[i]) dp[i][j] = dp[i - 1][j]; -else dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j - weight[i]] + value[i]); -} -} - -return dp[len-1][size] //满足条件的最大值 -} - -function testWeightBagProblem2 (wight, value, size) { - const len = wight.length, - dp = Array(size + 1).fill(0); - for(let i = 1; i <= len; i++) { - for(let j = size; j >= wight[i - 1]; j--) { - dp[j] = Math.max(dp[j], value[i - 1] + dp[j - wight[i - 1]]); + // 初始化 + for(let j = weight[0]; j <= size; j++) { + dp[0][j] = value[0]; } - } - return dp[size]; -} + // weight 数组的长度len 就是物品个数 + for(let i = 1; i < len; i++) { // 遍历物品 + for(let j = 0; j <= size; j++) { // 遍历背包容量 + if(j < weight[i]) dp[i][j] = dp[i - 1][j]; + else dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); + } + } + + console.table(dp) + + return dp[len - 1][size]; +} function test () { - console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); + console.log(testWeightBagProblem([1, 3, 4, 5], [15, 20, 30, 55], 6)); } test(); diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index 2fe9f14c..1a29c32a 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -210,6 +210,13 @@ type ListNode struct { } ``` +Scala: +```scala +class ListNode(_x: Int = 0, _next: ListNode = null) { + var next: ListNode = _next + var x: Int = _x +} +``` ----------------------- diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 2e7226de..1ae01061 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -7,7 +7,7 @@ # 面试题 02.07. 链表相交 -[力扣题目链接](https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/) +[力扣题目链接](https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/) 给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。 @@ -317,7 +317,55 @@ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { } ``` - +Scala: +```scala +object Solution { + def getIntersectionNode(headA: ListNode, headB: ListNode): ListNode = { + var lenA = 0 // headA链表的长度 + var lenB = 0 // headB链表的长度 + var tmp = headA // 临时变量 + // 统计headA的长度 + while (tmp != null) { + lenA += 1; + tmp = tmp.next + } + // 统计headB的长度 + tmp = headB // 临时变量赋值给headB + while (tmp != null) { + lenB += 1 + tmp = tmp.next + } + // 因为传递过来的参数是不可变量,所以需要重新定义 + var listA = headA + var listB = headB + // 两个链表的长度差 + // 如果gap>0,lenA>lenB,headA(listA)链表往前移动gap步 + // 如果gap<0,lenA 0) { + // 因为不可以i-=1,所以可以使用for + for (i <- 0 until gap) { + listA = listA.next // 链表headA(listA) 移动 + } + } else { + gap = math.abs(gap) // 此刻gap为负值,取绝对值 + for (i <- 0 until gap) { + listB = listB.next + } + } + // 现在两个链表同时往前走,如果相等则返回 + while (listA != null && listB != null) { + if (listA == listB) { + return listA + } + listA = listA.next + listB = listB.next + } + // 如果链表没有相交则返回null,return可以省略 + null + } +} +``` -----------------------