diff --git a/problems/0017.电话号码的字母组合.md b/problems/0017.电话号码的字母组合.md index 2b5cb978..e357a33b 100644 --- a/problems/0017.电话号码的字母组合.md +++ b/problems/0017.电话号码的字母组合.md @@ -557,6 +557,37 @@ func letterCombinations(_ digits: String) -> [String] { } ``` +## Scala: + +```scala +object Solution { + import scala.collection.mutable + def letterCombinations(digits: String): List[String] = { + var result = mutable.ListBuffer[String]() + if(digits == "") return result.toList // 如果参数为空,返回空结果集的List形式 + var path = mutable.ListBuffer[Char]() + // 数字和字符的映射关系 + val map = Array[String]("", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz") + + def backtracking(index: Int): Unit = { + if (index == digits.size) { + result.append(path.mkString) // mkString语法:将数组类型直接转换为字符串 + return + } + var digit = digits(index) - '0' // 这里使用toInt会报错!必须 -'0' + for (i <- 0 until map(digit).size) { + path.append(map(digit)(i)) + backtracking(index + 1) + path = path.take(path.size - 1) + } + } + + backtracking(0) + result.toList + } +} +``` + -----------------------
diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index e636bfff..7ef86562 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -254,20 +254,19 @@ TypeScript: ```typescript function swapPairs(head: ListNode | null): ListNode | null { - const dummyHead: ListNode = new ListNode(0, head); - let cur: ListNode = dummyHead; - while(cur.next !== null && cur.next.next !== null) { - const tem: ListNode = cur.next; - const tem1: ListNode = cur.next.next.next; - - cur.next = cur.next.next; // step 1 - cur.next.next = tem; // step 2 - cur.next.next.next = tem1; // step 3 - - cur = cur.next.next; - } - return dummyHead.next; -} + const dummyNode: ListNode = new ListNode(0, head); + let curNode: ListNode | null = dummyNode; + while (curNode && curNode.next && curNode.next.next) { + let firstNode: ListNode = curNode.next, + secNode: ListNode = curNode.next.next, + thirdNode: ListNode | null = curNode.next.next.next; + curNode.next = secNode; + secNode.next = firstNode; + firstNode.next = thirdNode; + curNode = firstNode; + } + return dummyNode.next; +}; ``` Kotlin: diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 03c58b43..9d687cfb 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -339,7 +339,6 @@ int removeElement(int* nums, int numsSize, int val){ } ``` - Kotlin: ```kotlin fun removeElement(nums: IntArray, `val`: Int): Int { @@ -351,7 +350,6 @@ fun removeElement(nums: IntArray, `val`: Int): Int { } ``` - Scala: ```scala object Solution { @@ -368,5 +366,20 @@ object Solution { } ``` +C#: +```csharp +public class Solution { + public int RemoveElement(int[] nums, int val) { + int slow = 0; + for (int fast = 0; fast < nums.Length; fast++) { + if (val != nums[fast]) { + nums[slow++] = nums[fast]; + } + } + return slow; + } +} +``` + -----------------------
diff --git a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md index 260462c2..a81b3641 100644 --- a/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md +++ b/problems/0034.在排序数组中查找元素的第一个和最后一个位置.md @@ -480,6 +480,62 @@ var searchRange = function(nums, target) { return [-1, -1]; }; ``` + + +### TypeScript + +```typescript +function searchRange(nums: number[], target: number): number[] { + const leftBoard: number = getLeftBorder(nums, target); + const rightBoard: number = getRightBorder(nums, target); + // target 在nums区间左侧或右侧 + if (leftBoard === (nums.length - 1) || rightBoard === 0) return [-1, -1]; + // target 不存在与nums范围内 + if (rightBoard - leftBoard <= 1) return [-1, -1]; + // target 存在于nums范围内 + return [leftBoard + 1, rightBoard - 1]; +}; +// 查找第一个大于target的元素下标 +function getRightBorder(nums: number[], target: number): number { + let left: number = 0, + right: number = nums.length - 1; + // 0表示target在nums区间的左边 + let rightBoard: number = 0; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + if (nums[mid] <= target) { + // 右边界一定在mid右边(不含mid) + left = mid + 1; + rightBoard = left; + } else { + // 右边界在mid左边(含mid) + right = mid - 1; + } + } + return rightBoard; +} +// 查找第一个小于target的元素下标 +function getLeftBorder(nums: number[], target: number): number { + let left: number = 0, + right: number = nums.length - 1; + // length-1表示target在nums区间的右边 + let leftBoard: number = nums.length - 1; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + if (nums[mid] >= target) { + // 左边界一定在mid左边(不含mid) + right = mid - 1; + leftBoard = right; + } else { + // 左边界在mid右边(含mid) + left = mid + 1; + } + } + return leftBoard; +} +``` + + ### Scala ```scala object Solution { @@ -527,5 +583,6 @@ object Solution { } ``` + -----------------------
diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index ed7c49b4..77def4f8 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -283,6 +283,28 @@ var searchInsert = function (nums, target) { }; ``` +### TypeScript + +```typescript +// 第一种二分法 +function searchInsert(nums: number[], target: number): number { + const length: number = nums.length; + let left: number = 0, + right: number = length - 1; + while (left <= right) { + const mid: number = Math.floor((left + right) / 2); + if (nums[mid] < target) { + left = mid + 1; + } else if (nums[mid] === target) { + return mid; + } else { + right = mid - 1; + } + } + return right + 1; +}; +``` + ### Swift ```swift diff --git a/problems/0039.组合总和.md b/problems/0039.组合总和.md index fef9b676..564d13ea 100644 --- a/problems/0039.组合总和.md +++ b/problems/0039.组合总和.md @@ -502,5 +502,35 @@ func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { } ``` +## Scala + +```scala +object Solution { + import scala.collection.mutable + def combinationSum(candidates: Array[Int], target: Int): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(sum: Int, index: Int): Unit = { + if (sum == target) { + result.append(path.toList) // 如果正好等于target,就添加到结果集 + return + } + // 应该是从当前索引开始的,而不是从0 + // 剪枝优化:添加循环守卫,当sum + c(i) <= target的时候才循环,才可以进入下一次递归 + for (i <- index until candidates.size if sum + candidates(i) <= target) { + path.append(candidates(i)) + backtracking(sum + candidates(i), i) + path = path.take(path.size - 1) + } + } + + backtracking(0, 0) + result.toList + } +} +``` + + -----------------------
diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index ee4371cd..557eb855 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -693,5 +693,37 @@ func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] { } ``` + +## Scala + +```scala +object Solution { + import scala.collection.mutable + def combinationSum2(candidates: Array[Int], target: Int): List[List[Int]] = { + var res = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + var candidate = candidates.sorted + + def backtracking(sum: Int, startIndex: Int): Unit = { + if (sum == target) { + res.append(path.toList) + return + } + + for (i <- startIndex until candidate.size if sum + candidate(i) <= target) { + if (!(i > startIndex && candidate(i) == candidate(i - 1))) { + path.append(candidate(i)) + backtracking(sum + candidate(i), i + 1) + path = path.take(path.size - 1) + } + } + } + + backtracking(0, 0) + res.toList + } +} +``` + -----------------------
diff --git a/problems/0077.组合.md b/problems/0077.组合.md index 8d22d018..fc72be15 100644 --- a/problems/0077.组合.md +++ b/problems/0077.组合.md @@ -673,5 +673,63 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] { } ``` +### Scala + +暴力: +```scala +object Solution { + import scala.collection.mutable // 导包 + def combine(n: Int, k: Int): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() // 存放结果集 + var path = mutable.ListBuffer[Int]() //存放符合条件的结果 + + def backtracking(n: Int, k: Int, startIndex: Int): Unit = { + if (path.size == k) { + // 如果path的size == k就达到题目要求,添加到结果集,并返回 + result.append(path.toList) + return + } + for (i <- startIndex to n) { // 遍历从startIndex到n + path.append(i) // 先把数字添加进去 + backtracking(n, k, i + 1) // 进行下一步回溯 + path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字 + } + } + + backtracking(n, k, 1) // 执行回溯 + result.toList // 最终返回result的List形式,return关键字可以省略 + } +} +``` + +剪枝: + +```scala +object Solution { + import scala.collection.mutable // 导包 + def combine(n: Int, k: Int): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() // 存放结果集 + var path = mutable.ListBuffer[Int]() //存放符合条件的结果 + + def backtracking(n: Int, k: Int, startIndex: Int): Unit = { + if (path.size == k) { + // 如果path的size == k就达到题目要求,添加到结果集,并返回 + result.append(path.toList) + return + } + // 剪枝优化 + for (i <- startIndex to (n - (k - path.size) + 1)) { + path.append(i) // 先把数字添加进去 + backtracking(n, k, i + 1) // 进行下一步回溯 + path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字 + } + } + + backtracking(n, k, 1) // 执行回溯 + result.toList // 最终返回result的List形式,return关键字可以省略 + } +} +``` + -----------------------
diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index a6767047..8d742566 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -346,5 +346,34 @@ func combine(_ n: Int, _ k: Int) -> [[Int]] { } ``` +Scala: + +```scala +object Solution { + import scala.collection.mutable // 导包 + def combine(n: Int, k: Int): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() // 存放结果集 + var path = mutable.ListBuffer[Int]() //存放符合条件的结果 + + def backtracking(n: Int, k: Int, startIndex: Int): Unit = { + if (path.size == k) { + // 如果path的size == k就达到题目要求,添加到结果集,并返回 + result.append(path.toList) + return + } + // 剪枝优化 + for (i <- startIndex to (n - (k - path.size) + 1)) { + path.append(i) // 先把数字添加进去 + backtracking(n, k, i + 1) // 进行下一步回溯 + path = path.take(path.size - 1) // 回溯完再删除掉刚刚添加的数字 + } + } + + backtracking(n, k, 1) // 执行回溯 + result.toList // 最终返回result的List形式,return关键字可以省略 + } +} +``` + -----------------------
diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 41940487..11ca2d03 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -659,6 +659,48 @@ func restoreIpAddresses(_ s: String) -> [String] { } ``` +## Scala + +```scala +object Solution { + import scala.collection.mutable + def restoreIpAddresses(s: String): List[String] = { + var result = mutable.ListBuffer[String]() + if (s.size < 4 || s.length > 12) return result.toList + var path = mutable.ListBuffer[String]() + + // 判断IP中的一个字段是否为正确的 + def isIP(sub: String): Boolean = { + if (sub.size > 1 && sub(0) == '0') return false + if (sub.toInt > 255) return false + true + } + + def backtracking(startIndex: Int): Unit = { + if (startIndex >= s.size) { + if (path.size == 4) { + result.append(path.mkString(".")) // mkString方法可以把集合里的数据以指定字符串拼接 + return + } + return + } + // subString + for (i <- startIndex until startIndex + 3 if i < s.size) { + var subString = s.substring(startIndex, i + 1) + if (isIP(subString)) { // 如果合法则进行下一轮 + path.append(subString) + backtracking(i + 1) + path = path.take(path.size - 1) + } + } + } + + backtracking(0) + result.toList + } +} +``` + -----------------------
diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index 6d87c756..91e0c8d8 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -584,35 +584,29 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。 ```java class Solution { + Map map; // 方便根据数值查找位置 public TreeNode buildTree(int[] inorder, int[] postorder) { - return buildTree1(inorder, 0, inorder.length, postorder, 0, postorder.length); + map = new HashMap<>(); + for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置 + map.put(inorder[i], i); + } + + return findNode(inorder, 0, inorder.length, postorder,0, postorder.length); // 前闭后开 } - public TreeNode buildTree1(int[] inorder, int inLeft, int inRight, - int[] postorder, int postLeft, int postRight) { - // 没有元素了 - if (inRight - inLeft < 1) { + + public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) { + // 参数里的范围都是前闭后开 + if (inBegin >= inEnd || postBegin >= postEnd) { // 不满足左闭右开,说明没有元素,返回空树 return null; } - // 只有一个元素了 - if (inRight - inLeft == 1) { - return new TreeNode(inorder[inLeft]); - } - // 后序数组postorder里最后一个即为根结点 - int rootVal = postorder[postRight - 1]; - TreeNode root = new TreeNode(rootVal); - int rootIndex = 0; - // 根据根结点的值找到该值在中序数组inorder里的位置 - for (int i = inLeft; i < inRight; i++) { - if (inorder[i] == rootVal) { - rootIndex = i; - break; - } - } - // 根据rootIndex划分左右子树 - root.left = buildTree1(inorder, inLeft, rootIndex, - postorder, postLeft, postLeft + (rootIndex - inLeft)); - root.right = buildTree1(inorder, rootIndex + 1, inRight, - postorder, postLeft + (rootIndex - inLeft), postRight - 1); + int rootIndex = map.get(postorder[postEnd - 1]); // 找到后序遍历的最后一个元素在中序遍历中的位置 + TreeNode root = new TreeNode(inorder[rootIndex]); // 构造结点 + int lenOfLeft = rootIndex - inBegin; // 保存中序左子树个数,用来确定后序数列的个数 + root.left = findNode(inorder, inBegin, rootIndex, + postorder, postBegin, postBegin + lenOfLeft); + root.right = findNode(inorder, rootIndex + 1, inEnd, + postorder, postBegin + lenOfLeft, postEnd - 1); + return root; } } @@ -622,31 +616,29 @@ class Solution { ```java class Solution { + Map map; public TreeNode buildTree(int[] preorder, int[] inorder) { - return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); - } - - public TreeNode helper(int[] preorder, int preLeft, int preRight, - int[] inorder, int inLeft, int inRight) { - // 递归终止条件 - if (inLeft > inRight || preLeft > preRight) return null; - - // val 为前序遍历第一个的值,也即是根节点的值 - // idx 为根据根节点的值来找中序遍历的下标 - int idx = inLeft, val = preorder[preLeft]; - TreeNode root = new TreeNode(val); - for (int i = inLeft; i <= inRight; i++) { - if (inorder[i] == val) { - idx = i; - break; - } + map = new HashMap<>(); + for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置 + map.put(inorder[i], i); } - // 根据 idx 来递归找左右子树 - root.left = helper(preorder, preLeft + 1, preLeft + (idx - inLeft), - inorder, inLeft, idx - 1); - root.right = helper(preorder, preLeft + (idx - inLeft) + 1, preRight, - inorder, idx + 1, inRight); + return findNode(preorder, 0, preorder.length, inorder, 0, inorder.length); // 前闭后开 + } + + public TreeNode findNode(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd) { + // 参数里的范围都是前闭后开 + if (preBegin >= preEnd || inBegin >= inEnd) { // 不满足左闭右开,说明没有元素,返回空树 + return null; + } + int rootIndex = map.get(preorder[preBegin]); // 找到前序遍历的第一个元素在中序遍历中的位置 + TreeNode root = new TreeNode(inorder[rootIndex]); // 构造结点 + int lenOfLeft = rootIndex - inBegin; // 保存中序左子树个数,用来确定前序数列的个数 + root.left = findNode(preorder, preBegin + 1, preBegin + lenOfLeft + 1, + inorder, inBegin, rootIndex); + root.right = findNode(preorder, preBegin + lenOfLeft + 1, preEnd, + inorder, rootIndex + 1, inEnd); + return root; } } diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index c9c1a693..b5f322f0 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -448,5 +448,27 @@ struct TreeNode* sortedArrayToBST(int* nums, int numsSize) { } ``` +## Scala + +递归: + +```scala +object Solution { + def sortedArrayToBST(nums: Array[Int]): TreeNode = { + def buildTree(left: Int, right: Int): TreeNode = { + if (left > right) return null // 当left大于right的时候,返回空 + // 最中间的节点是当前节点 + var mid = left + (right - left) / 2 + var curNode = new TreeNode(nums(mid)) + curNode.left = buildTree(left, mid - 1) + curNode.right = buildTree(mid + 1, right) + curNode + } + buildTree(0, nums.size - 1) + } +} +``` + + -----------------------
diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index a371864d..64d45853 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -676,5 +676,50 @@ impl Solution { } } ``` + + +## Scala + +```scala +object Solution { + + import scala.collection.mutable + + def partition(s: String): List[List[String]] = { + var result = mutable.ListBuffer[List[String]]() + var path = mutable.ListBuffer[String]() + + // 判断字符串是否回文 + def isPalindrome(start: Int, end: Int): Boolean = { + var (left, right) = (start, end) + while (left < right) { + if (s(left) != s(right)) return false + left += 1 + right -= 1 + } + true + } + + // 回溯算法 + def backtracking(startIndex: Int): Unit = { + if (startIndex >= s.size) { + result.append(path.toList) + return + } + // 添加循环守卫,如果当前分割是回文子串则进入回溯 + for (i <- startIndex until s.size if isPalindrome(startIndex, i)) { + path.append(s.substring(startIndex, i + 1)) + backtracking(i + 1) + path = path.take(path.size - 1) + } + } + + backtracking(0) + result.toList + } +} +``` + + -----------------------
diff --git a/problems/0141.环形链表.md b/problems/0141.环形链表.md index ddd83c94..ce90b6c4 100644 --- a/problems/0141.环形链表.md +++ b/problems/0141.环形链表.md @@ -7,6 +7,8 @@ # 141. 环形链表 +[力扣题目链接](https://leetcode.cn/problems/linked-list-cycle/submissions/) + 给定一个链表,判断链表中是否有环。 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。 @@ -103,7 +105,7 @@ class Solution: return False ``` -## Go +### Go ```go func hasCycle(head *ListNode) bool { @@ -139,6 +141,23 @@ var hasCycle = function(head) { }; ``` +### TypeScript + +```typescript +function hasCycle(head: ListNode | null): boolean { + let slowNode: ListNode | null = head, + fastNode: ListNode | null = head; + while (fastNode !== null && fastNode.next !== null) { + slowNode = slowNode!.next; + fastNode = fastNode.next.next; + if (slowNode === fastNode) return true; + } + return false; +}; +``` + + + -----------------------
diff --git a/problems/0142.环形链表II.md b/problems/0142.环形链表II.md index 6b7c7e66..658bd868 100644 --- a/problems/0142.环形链表II.md +++ b/problems/0142.环形链表II.md @@ -301,13 +301,13 @@ function detectCycle(head: ListNode | null): ListNode | null { let slowNode: ListNode | null = head, fastNode: ListNode | null = head; while (fastNode !== null && fastNode.next !== null) { - slowNode = (slowNode as ListNode).next; + slowNode = slowNode!.next; fastNode = fastNode.next.next; if (slowNode === fastNode) { slowNode = head; while (slowNode !== fastNode) { - slowNode = (slowNode as ListNode).next; - fastNode = (fastNode as ListNode).next; + slowNode = slowNode!.next; + fastNode = fastNode!.next; } return slowNode; } diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index 790bcb48..c60fc0f9 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -6,6 +6,8 @@ # 143.重排链表 +[力扣题目链接](https://leetcode.cn/problems/reorder-list/submissions/) + ![](https://code-thinking-1253855093.file.myqcloud.com/pics/20210726160122.png) ## 思路 @@ -465,7 +467,81 @@ var reorderList = function(head, s = [], tmp) { } ``` +### TypeScript + +> 辅助数组法: + +```typescript +function reorderList(head: ListNode | null): void { + if (head === null) return; + const helperArr: ListNode[] = []; + let curNode: ListNode | null = head; + while (curNode !== null) { + helperArr.push(curNode); + curNode = curNode.next; + } + let node: ListNode = head; + let left: number = 1, + right: number = helperArr.length - 1; + let count: number = 0; + while (left <= right) { + if (count % 2 === 0) { + node.next = helperArr[right--]; + } else { + node.next = helperArr[left++]; + } + count++; + node = node.next; + } + node.next = null; +}; +``` + +> 分割链表法: + +```typescript +function reorderList(head: ListNode | null): void { + if (head === null || head.next === null) return; + let fastNode: ListNode = head, + slowNode: ListNode = head; + while (fastNode.next !== null && fastNode.next.next !== null) { + slowNode = slowNode.next!; + fastNode = fastNode.next.next; + } + let head1: ListNode | null = head; + // 反转后半部分链表 + let head2: ListNode | null = reverseList(slowNode.next); + // 分割链表 + slowNode.next = null; + /** + 直接在head1链表上进行插入 + head1 链表长度一定大于或等于head2, + 因此在下面的循环中,只要head2不为null, head1 一定不为null + */ + while (head2 !== null) { + const tempNode1: ListNode | null = head1!.next, + tempNode2: ListNode | null = head2.next; + head1!.next = head2; + head2.next = tempNode1; + head1 = tempNode1; + head2 = tempNode2; + } +}; +function reverseList(head: ListNode | null): ListNode | null { + let curNode: ListNode | null = head, + preNode: ListNode | null = null; + while (curNode !== null) { + const tempNode: ListNode | null = curNode.next; + curNode.next = preNode; + preNode = curNode; + curNode = tempNode; + } + return preNode; +} +``` + ### C + 方法三:反转链表 ```c //翻转链表 diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index 05916135..1a90265a 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -325,6 +325,33 @@ func evalRPN(_ tokens: [String]) -> Int { return stack.last! } ``` + + +PHP: +```php +class Solution { + function evalRPN($tokens) { + $st = new SplStack(); + for($i = 0;$ipush($tokens[$i]); + }else{ + // 是符号进行运算 + $num1 = $st->pop(); + $num2 = $st->pop(); + if ($tokens[$i] == "+") $st->push($num2 + $num1); + if ($tokens[$i] == "-") $st->push($num2 - $num1); + if ($tokens[$i] == "*") $st->push($num2 * $num1); + // 注意处理小数部分 + if ($tokens[$i] == "/") $st->push(intval($num2 / $num1)); + } + } + return $st->pop(); + } +} +``` + Scala: ```scala object Solution { @@ -351,6 +378,7 @@ object Solution { // 最后返回栈顶,不需要加return关键字 stack.pop() } + } ``` ----------------------- diff --git a/problems/0209.长度最小的子数组.md b/problems/0209.长度最小的子数组.md index e2eb378e..090e73f0 100644 --- a/problems/0209.长度最小的子数组.md +++ b/problems/0209.长度最小的子数组.md @@ -465,6 +465,27 @@ object Solution { } } ``` - +C#: +```csharp +public class Solution { + public int MinSubArrayLen(int s, int[] nums) { + int n = nums.Length; + int ans = int.MaxValue; + int start = 0, end = 0; + int sum = 0; + while (end < n) { + sum += nums[end]; + while (sum >= s) + { + ans = Math.Min(ans, end - start + 1); + sum -= nums[start]; + start++; + } + end++; + } + return ans == int.MaxValue ? 0 : ans; + } +} +``` -----------------------
diff --git a/problems/0216.组合总和III.md b/problems/0216.组合总和III.md index 0ace0fd5..2c1bf717 100644 --- a/problems/0216.组合总和III.md +++ b/problems/0216.组合总和III.md @@ -502,5 +502,35 @@ func combinationSum3(_ count: Int, _ targetSum: Int) -> [[Int]] { } ``` +## Scala + +```scala +object Solution { + import scala.collection.mutable + def combinationSum3(k: Int, n: Int): List[List[Int]] = { + var result = mutable.ListBuffer[List[Int]]() + var path = mutable.ListBuffer[Int]() + + def backtracking(k: Int, n: Int, sum: Int, startIndex: Int): Unit = { + if (sum > n) return // 剪枝,如果sum>目标和,就返回 + if (sum == n && path.size == k) { + result.append(path.toList) + return + } + // 剪枝 + for (i <- startIndex to (9 - (k - path.size) + 1)) { + path.append(i) + backtracking(k, n, sum + i, i + 1) + path = path.take(path.size - 1) + } + } + + backtracking(k, n, 0, 1) // 调用递归方法 + result.toList // 最终返回结果集的List形式 + } +} +``` + + -----------------------
diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index f591fcef..eeee6fa5 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -273,7 +273,7 @@ class Solution: return pre ``` -## Go +### Go ```go @@ -319,6 +319,63 @@ var isPalindrome = function(head) { }; ``` +### TypeScript + +> 数组模拟 + +```typescript +function isPalindrome(head: ListNode | null): boolean { + const helperArr: number[] = []; + let curNode: ListNode | null = head; + while (curNode !== null) { + helperArr.push(curNode.val); + curNode = curNode.next; + } + let left: number = 0, + right: number = helperArr.length - 1; + while (left < right) { + if (helperArr[left++] !== helperArr[right--]) return false; + } + return true; +}; +``` + +> 反转后半部分链表 + +```typescript +function isPalindrome(head: ListNode | null): boolean { + if (head === null || head.next === null) return true; + let fastNode: ListNode | null = head, + slowNode: ListNode = head, + preNode: ListNode = head; + while (fastNode !== null && fastNode.next !== null) { + preNode = slowNode; + slowNode = slowNode.next!; + fastNode = fastNode.next.next; + } + preNode.next = null; + let cur1: ListNode | null = head; + let cur2: ListNode | null = reverseList(slowNode); + while (cur1 !== null) { + if (cur1.val !== cur2!.val) return false; + cur1 = cur1.next; + cur2 = cur2!.next; + } + return true; +}; +function reverseList(head: ListNode | null): ListNode | null { + let curNode: ListNode | null = head, + preNode: ListNode | null = null; + while (curNode !== null) { + let tempNode: ListNode | null = curNode.next; + curNode.next = preNode; + preNode = curNode; + curNode = tempNode; + } + return preNode; +} +``` + ----------------------- diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index 9ff7e293..ee86d02f 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -381,7 +381,36 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree }; ``` +## Scala +递归: + +```scala +object Solution { + def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = { + // scala中每个关键字都有其返回值,于是可以不写return + if (root.value > p.value && root.value > q.value) lowestCommonAncestor(root.left, p, q) + else if (root.value < p.value && root.value < q.value) lowestCommonAncestor(root.right, p, q) + else root + } +} +``` + +迭代: + +```scala +object Solution { + def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = { + var curNode = root // 因为root是不可变量,所以要赋值给curNode一个可变量 + while(curNode != null){ + if(curNode.value > p.value && curNode.value > q.value) curNode = curNode.left + else if(curNode.value < p.value && curNode.value < q.value) curNode = curNode.right + else return curNode + } + null + } +} +``` ----------------------- diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 23695b11..c3e2ae7a 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -343,7 +343,25 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree }; ``` +## Scala +```scala +object Solution { + def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = { + // 递归结束条件 + if (root == null || root == p || root == q) { + return root + } + + var left = lowestCommonAncestor(root.left, p, q) + var right = lowestCommonAncestor(root.right, p, q) + + if (left != null && right != null) return root + if (left == null) return right + left + } +} +``` -----------------------
diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 23e79c80..7ee1fdb1 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -654,8 +654,7 @@ object Solution { // 最终返回res,return关键字可以省略 res } - -} + } class MyQueue { var queue = ArrayBuffer[Int]() @@ -678,5 +677,84 @@ class MyQueue { def peek(): Int = queue.head } ``` + + +PHP: +```php +class Solution { + /** + * @param Integer[] $nums + * @param Integer $k + * @return Integer[] + */ + function maxSlidingWindow($nums, $k) { + $myQueue = new MyQueue(); + // 先将前k的元素放进队列 + for ($i = 0; $i < $k; $i++) { + $myQueue->push($nums[$i]); + } + + $result = []; + $result[] = $myQueue->max(); // result 记录前k的元素的最大值 + + for ($i = $k; $i < count($nums); $i++) { + $myQueue->pop($nums[$i - $k]); // 滑动窗口移除最前面元素 + $myQueue->push($nums[$i]); // 滑动窗口前加入最后面的元素 + $result[]= $myQueue->max(); // 记录对应的最大值 + } + return $result; + } + +} + +// 单调对列构建 +class MyQueue{ + private $queue; + + public function __construct(){ + $this->queue = new SplQueue(); //底层是双向链表实现。 + } + + public function pop($v){ + // 判断当前对列是否为空 + // 比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。 + // bottom 从链表前端查看元素, dequeue 从双向链表的开头移动一个节点 + if(!$this->queue->isEmpty() && $v == $this->queue->bottom()){ + $this->queue->dequeue(); //弹出队列 + } + } + + public function push($v){ + // 判断当前对列是否为空 + // 如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。 + // 这样就保持了队列里的数值是单调从大到小的了。 + while (!$this->queue->isEmpty() && $v > $this->queue->top()) { + $this->queue->pop(); // pop从链表末尾弹出一个元素, + } + $this->queue->enqueue($v); + } + + // 查询当前队列里的最大值 直接返回队首 + public function max(){ + // bottom 从链表前端查看元素, top从链表末尾查看元素 + return $this->queue->bottom(); + } + + // 辅助理解: 打印队列元素 + public function println(){ + // "迭代器移动到链表头部": 可理解为从头遍历链表元素做准备。 + // 【PHP中没有指针概念,所以就没说指针。从数据结构上理解,就是把指针指向链表头部】 + $this->queue->rewind(); + + echo "Println: "; + while($this->queue->valid()){ + echo $this->queue->current()," -> "; + $this->queue->next(); + } + echo "\n"; + } +} +``` + -----------------------
diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index aba6e2f3..90dbcc0e 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -190,13 +190,13 @@ javaScript: * @return {void} Do not return anything, modify s in-place instead. */ var reverseString = function(s) { - return s.reverse(); + //Do not return anything, modify s in-place instead. + reverse(s) }; -var reverseString = function(s) { +var reverse = function(s) { let l = -1, r = s.length; while(++l < --r) [s[l], s[r]] = [s[r], s[l]]; - return s; }; ``` diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index aca9084f..3fa2a1c5 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -582,7 +582,35 @@ function deleteNode(root: TreeNode | null, key: number): TreeNode | null { }; ``` +## Scala +```scala +object Solution { + def deleteNode(root: TreeNode, key: Int): TreeNode = { + if (root == null) return root // 第一种情况,没找到删除的节点,遍历到空节点直接返回 + if (root.value == key) { + // 第二种情况: 左右孩子都为空,直接删除节点,返回null + if (root.left == null && root.right == null) return null + // 第三种情况: 左孩子为空,右孩子不为空,右孩子补位 + else if (root.left == null && root.right != null) return root.right + // 第四种情况: 左孩子不为空,右孩子为空,左孩子补位 + else if (root.left != null && root.right == null) return root.left + // 第五种情况: 左右孩子都不为空,将删除节点的左子树头节点(左孩子)放到 + // 右子树的最左边节点的左孩子上,返回删除节点的右孩子 + else { + var tmp = root.right + while (tmp.left != null) tmp = tmp.left + tmp.left = root.left + return root.right + } + } + if (root.value > key) root.left = deleteNode(root.left, key) + if (root.value < key) root.right = deleteNode(root.right, key) + + root // 返回根节点,return关键字可以省略 + } +} +``` -----------------------
diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 853cca6f..5c1e9e8c 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -352,6 +352,24 @@ function convertBST(root: TreeNode | null): TreeNode | null { }; ``` +## Scala + +```scala +object Solution { + def convertBST(root: TreeNode): TreeNode = { + var sum = 0 + def convert(node: TreeNode): Unit = { + if (node == null) return + convert(node.right) + sum += node.value + node.value = sum + convert(node.left) + } + convert(root) + root + } +} +``` ----------------------- diff --git a/problems/0669.修剪二叉搜索树.md b/problems/0669.修剪二叉搜索树.md index 154ba5a9..a286315d 100644 --- a/problems/0669.修剪二叉搜索树.md +++ b/problems/0669.修剪二叉搜索树.md @@ -453,7 +453,21 @@ function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | n }; ``` +## Scala +递归法: +```scala +object Solution { + def trimBST(root: TreeNode, low: Int, high: Int): TreeNode = { + if (root == null) return null + if (root.value < low) return trimBST(root.right, low, high) + if (root.value > high) return trimBST(root.left, low, high) + root.left = trimBST(root.left, low, high) + root.right = trimBST(root.right, low, high) + root + } +} +``` ----------------------- diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 102f091e..06e1c88f 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -585,6 +585,43 @@ function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { ``` +## Scala + +递归: + +```scala +object Solution { + def insertIntoBST(root: TreeNode, `val`: Int): TreeNode = { + if (root == null) return new TreeNode(`val`) + if (`val` < root.value) root.left = insertIntoBST(root.left, `val`) + else root.right = insertIntoBST(root.right, `val`) + root // 返回根节点 + } +} +``` + +迭代: + +```scala +object Solution { + def insertIntoBST(root: TreeNode, `val`: Int): TreeNode = { + if (root == null) { + return new TreeNode(`val`) + } + var parent = root // 记录当前节点的父节点 + var curNode = root + while (curNode != null) { + parent = curNode + if(`val` < curNode.value) curNode = curNode.left + else curNode = curNode.right + } + if(`val` < parent.value) parent.left = new TreeNode(`val`) + else parent.right = new TreeNode(`val`) + root // 最终返回根节点 + } +} +``` + -----------------------
diff --git a/problems/0704.二分查找.md b/problems/0704.二分查找.md index 6a37e4d1..f3b9326d 100644 --- a/problems/0704.二分查找.md +++ b/problems/0704.二分查找.md @@ -613,6 +613,36 @@ public class Solution{ } ``` +**Kotlin:** +```kotlin +class Solution { + fun search(nums: IntArray, target: Int): Int { + // leftBorder + var left:Int = 0 + // rightBorder + var right:Int = nums.size - 1 + // 使用左闭右闭区间 + while (left <= right) { + var middle:Int = left + (right - left)/2 + // taget 在左边 + if (nums[middle] > target) { + right = middle - 1 + } + else { + // target 在右边 + if (nums[middle] < target) { + left = middle + 1 + } + // 找到了,返回 + else return middle + } + } + // 没找到,返回 + return -1 + } +} +``` + **Kotlin:** diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 6ee11eef..42e3fc09 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -104,8 +104,9 @@ public: // 在第index个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。 // 如果index 等于链表的长度,则说明是新插入的节点为链表的尾结点 // 如果index大于链表的长度,则返回空 + // 如果index小于0,则置为0,作为链表的新头节点。 void addAtIndex(int index, int val) { - if (index > _size) { + if (index > _size || index < 0) { return; } LinkedNode* newNode = new LinkedNode(val); diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index 8ca46db9..49547a15 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -260,6 +260,75 @@ var sortArrayByParityII = function(nums) { }; ``` +### TypeScript + +> 方法一: + +```typescript +function sortArrayByParityII(nums: number[]): number[] { + const evenArr: number[] = [], + oddArr: number[] = []; + for (let num of nums) { + if (num % 2 === 0) { + evenArr.push(num); + } else { + oddArr.push(num); + } + } + const resArr: number[] = []; + for (let i = 0, length = nums.length / 2; i < length; i++) { + resArr.push(evenArr[i]); + resArr.push(oddArr[i]); + } + return resArr; +}; +``` + +> 方法二: + +```typescript +function sortArrayByParityII(nums: number[]): number[] { + const length: number = nums.length; + const resArr: number[] = []; + let evenIndex: number = 0, + oddIndex: number = 1; + for (let i = 0; i < length; i++) { + if (nums[i] % 2 === 0) { + resArr[evenIndex] = nums[i]; + evenIndex += 2; + } else { + resArr[oddIndex] = nums[i]; + oddIndex += 2; + } + } + return resArr; +}; +``` + +> 方法三: + +```typescript +function sortArrayByParityII(nums: number[]): number[] { + const length: number = nums.length; + let oddIndex: number = 1; + for (let evenIndex = 0; evenIndex < length; evenIndex += 2) { + if (nums[evenIndex] % 2 === 1) { + // 在偶数位遇到了奇数 + while (oddIndex < length && nums[oddIndex] % 2 === 1) { + oddIndex += 2; + } + // 在奇数位遇到了偶数,交换 + let temp = nums[evenIndex]; + nums[evenIndex] = nums[oddIndex]; + nums[oddIndex] = temp; + } + } + return nums; +}; +``` + + + -----------------------
diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 19319205..59816eb3 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -421,6 +421,24 @@ object Solution { } ``` - +C#: +```csharp +public class Solution { + public int[] SortedSquares(int[] nums) { + int k = nums.Length - 1; + int[] result = new int[nums.Length]; + for (int i = 0, j = nums.Length - 1;i <= j;){ + if (nums[i] * nums[i] < nums[j] * nums[j]) { + result[k--] = nums[j] * nums[j]; + j--; + } else { + result[k--] = nums[i] * nums[i]; + i++; + } + } + return result; + } +} +``` -----------------------
diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index a40a92ab..e24824b9 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -356,9 +356,13 @@ func test_2_wei_bag_problem1(weight, value []int, bagweight int) int { // 递推公式 for i := 1; i < len(weight); i++ { //正序,也可以倒序 - for j := weight[i];j<= bagweight ; j++ { - dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]) - } + for j := 0; j <= bagweight; j++ { + if j < weight[i] { + dp[i][j] = dp[i-1][j] + } else { + dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]) + } + } } return dp[len(weight)-1][bagweight] }