diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index dd9155c6..3a776837 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -106,6 +106,37 @@ public: 旧文链接:[数组:就移除个元素很难么?](https://programmercarl.com/0027.移除元素.html) +```CPP +/** +* 相向双指针方法,基于元素顺序可以改变的题目描述改变了元素相对位置,确保了移动最少元素 +* 时间复杂度:$O(n)$ +* 空间复杂度:$O(1)$ +*/ +class Solution { +public: + int removeElement(vector& nums, int val) { + int leftIndex = 0; + int rightIndex = nums.size() - 1; + while (leftIndex <= rightIndex) { + // 找左边等于val的元素 + while (leftIndex <= rightIndex && nums[leftIndex] != val){ + ++leftIndex; + } + // 找右边不等于val的元素 + while (leftIndex <= rightIndex && nums[rightIndex] == val) { + -- rightIndex; + } + // 将右边不等于val的元素覆盖左边等于val的元素 + if (leftIndex < rightIndex) { + nums[leftIndex++] = nums[rightIndex--]; + } + } + return leftIndex; // leftIndex一定指向了最终数组末尾的下一个元素 + } +}; +``` + + ## 相关题目推荐 * 26.删除排序数组中的重复项 diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 84ed3932..12c62c70 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -433,6 +433,51 @@ var findBottomLeftValue = function(root) { }; ``` +## TypeScript + +> 递归法: + +```typescript +function findBottomLeftValue(root: TreeNode | null): number { + function recur(root: TreeNode, depth: number): void { + if (root.left === null && root.right === null) { + if (depth > maxDepth) { + maxDepth = depth; + resVal = root.val; + } + return; + } + if (root.left !== null) recur(root.left, depth + 1); + if (root.right !== null) recur(root.right, depth + 1); + } + let maxDepth: number = 0; + let resVal: number = 0; + if (root === null) return resVal; + recur(root, 1); + return resVal; +}; +``` + +> 迭代法: + +```typescript +function findBottomLeftValue(root: TreeNode | null): number { + let helperQueue: TreeNode[] = []; + if (root !== null) helperQueue.push(root); + let resVal: number = 0; + let tempNode: TreeNode; + while (helperQueue.length > 0) { + resVal = helperQueue[0].val; + for (let i = 0, length = helperQueue.length; i < length; i++) { + tempNode = helperQueue.shift()!; + if (tempNode.left !== null) helperQueue.push(tempNode.left); + if (tempNode.right !== null) helperQueue.push(tempNode.right); + } + } + return resVal; +}; +``` + ## Swift 递归版本: diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 468f2675..5e9fbdfe 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -310,6 +310,26 @@ class Solution: return root ``` +**递归法** - 无返回值 - another easier way +```python +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + newNode = TreeNode(val) + if not root: return newNode + + if not root.left and val < root.val: + root.left = newNode + if not root.right and val > root.val: + root.right = newNode + + if val < root.val: + self.insertIntoBST(root.left, val) + if val > root.val: + self.insertIntoBST(root.right, val) + + return root +``` + **迭代法** 与无返回值的递归函数的思路大体一致 ```python