mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -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
|
||||
|
@ -400,6 +400,37 @@ bool isValid(char * s){
|
||||
return !stackTop;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
// https://www.php.net/manual/zh/class.splstack.php
|
||||
class Solution
|
||||
{
|
||||
function isValid($s){
|
||||
$stack = new SplStack();
|
||||
for ($i = 0; $i < strlen($s); $i++) {
|
||||
if ($s[$i] == "(") {
|
||||
$stack->push(')');
|
||||
} else if ($s[$i] == "{") {
|
||||
$stack->push('}');
|
||||
} else if ($s[$i] == "[") {
|
||||
$stack->push(']');
|
||||
// 2、遍历匹配过程中,发现栈内没有要匹配的字符 return false
|
||||
// 3、遍历匹配过程中,栈已为空,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
|
||||
} else if ($stack->isEmpty() || $stack->top() != $s[$i]) {
|
||||
return false;
|
||||
} else {//$stack->top() == $s[$i]
|
||||
$stack->pop();
|
||||
}
|
||||
}
|
||||
// 1、遍历完,但是栈不为空,说明有相应的括号没有被匹配,return false
|
||||
return $stack->isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
object Solution {
|
||||
@ -422,5 +453,6 @@ object Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -480,6 +480,62 @@ var searchRange = function(nums, target) {
|
||||
return [-1, -1];
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
### TypeScript
|
||||
|
||||
```typescript
|
||||
function searchRange(nums: number[], target: number): number[] {
|
||||
const leftBoard: number = getLeftBorder(nums, target);
|
||||
const rightBoard: number = getRightBorder(nums, target);
|
||||
// target 在nums区间左侧或右侧
|
||||
if (leftBoard === (nums.length - 1) || rightBoard === 0) return [-1, -1];
|
||||
// target 不存在与nums范围内
|
||||
if (rightBoard - leftBoard <= 1) return [-1, -1];
|
||||
// target 存在于nums范围内
|
||||
return [leftBoard + 1, rightBoard - 1];
|
||||
};
|
||||
// 查找第一个大于target的元素下标
|
||||
function getRightBorder(nums: number[], target: number): number {
|
||||
let left: number = 0,
|
||||
right: number = nums.length - 1;
|
||||
// 0表示target在nums区间的左边
|
||||
let rightBoard: number = 0;
|
||||
while (left <= right) {
|
||||
let mid = Math.floor((left + right) / 2);
|
||||
if (nums[mid] <= target) {
|
||||
// 右边界一定在mid右边(不含mid)
|
||||
left = mid + 1;
|
||||
rightBoard = left;
|
||||
} else {
|
||||
// 右边界在mid左边(含mid)
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
return rightBoard;
|
||||
}
|
||||
// 查找第一个小于target的元素下标
|
||||
function getLeftBorder(nums: number[], target: number): number {
|
||||
let left: number = 0,
|
||||
right: number = nums.length - 1;
|
||||
// length-1表示target在nums区间的右边
|
||||
let leftBoard: number = nums.length - 1;
|
||||
while (left <= right) {
|
||||
let mid = Math.floor((left + right) / 2);
|
||||
if (nums[mid] >= target) {
|
||||
// 左边界一定在mid左边(不含mid)
|
||||
right = mid - 1;
|
||||
leftBoard = right;
|
||||
} else {
|
||||
// 左边界在mid右边(含mid)
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
return leftBoard;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Scala
|
||||
```scala
|
||||
object Solution {
|
||||
@ -527,5 +583,6 @@ object Solution {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -589,7 +589,50 @@ function isValidBST(root: TreeNode | null): boolean {
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
辅助数组解决:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def isValidBST(root: TreeNode): Boolean = {
|
||||
var arr = new mutable.ArrayBuffer[Int]()
|
||||
// 递归中序遍历二叉树,将节点添加到arr
|
||||
def traversal(node: TreeNode): Unit = {
|
||||
if (node == null) return
|
||||
traversal(node.left)
|
||||
arr.append(node.value)
|
||||
traversal(node.right)
|
||||
}
|
||||
traversal(root)
|
||||
// 这个数组如果是升序就代表是二叉搜索树
|
||||
for (i <- 1 until arr.size) {
|
||||
if (arr(i) <= arr(i - 1)) return false
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
递归中解决:
|
||||
```scala
|
||||
object Solution {
|
||||
def isValidBST(root: TreeNode): Boolean = {
|
||||
var flag = true
|
||||
var preValue:Long = Long.MinValue // 这里要使用Long类型
|
||||
|
||||
def traversal(node: TreeNode): Unit = {
|
||||
if (node == null || flag == false) return
|
||||
traversal(node.left)
|
||||
if (node.value > preValue) preValue = node.value
|
||||
else flag = false
|
||||
traversal(node.right)
|
||||
}
|
||||
traversal(root)
|
||||
flag
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -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--;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -816,7 +816,6 @@ class MyStack {
|
||||
}
|
||||
```
|
||||
Scala:
|
||||
|
||||
使用两个队列模拟栈:
|
||||
```scala
|
||||
import scala.collection.mutable
|
||||
@ -897,6 +896,86 @@ class MyStack() {
|
||||
def empty(): Boolean = {
|
||||
queue.isEmpty
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP
|
||||
> 双对列
|
||||
```php
|
||||
// SplQueue 类通过使用一个双向链表来提供队列的主要功能。(PHP 5 >= 5.3.0, PHP 7, PHP 8)
|
||||
// https://www.php.net/manual/zh/class.splqueue.php
|
||||
class MyStack {
|
||||
public $queueMain; // 保存数据
|
||||
public $queueTmp; // 辅助作用
|
||||
|
||||
function __construct() {
|
||||
$this->queueMain=new SplQueue();
|
||||
$this->queueTmp=new SplQueue();
|
||||
}
|
||||
|
||||
// queueMain: 1,2,3 <= add
|
||||
function push($x) {
|
||||
$this->queueMain->enqueue($x);
|
||||
}
|
||||
|
||||
function pop() {
|
||||
$qmSize = $this->queueMain->Count();
|
||||
$qmSize --;
|
||||
// queueMain: 3,2,1 => pop =>2,1 => add => 2,1 :queueTmp
|
||||
while($qmSize --){
|
||||
$this->queueTmp->enqueue($this->queueMain->dequeue());
|
||||
}
|
||||
// queueMain: 3
|
||||
$val = $this->queueMain->dequeue();
|
||||
// queueMain <= queueTmp
|
||||
$this->queueMain = $this->queueTmp;
|
||||
// 清空queueTmp,下次使用
|
||||
$this->queueTmp = new SplQueue();
|
||||
return $val;
|
||||
}
|
||||
|
||||
function top() {
|
||||
// 底层是双链表实现:从双链表的末尾查看节点
|
||||
return $this->queueMain->top();
|
||||
}
|
||||
|
||||
function empty() {
|
||||
return $this->queueMain->isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
> 单对列
|
||||
```php
|
||||
class MyStack {
|
||||
public $queue;
|
||||
|
||||
function __construct() {
|
||||
$this->queue=new SplQueue();
|
||||
}
|
||||
|
||||
function push($x) {
|
||||
$this->queue->enqueue($x);
|
||||
}
|
||||
|
||||
function pop() {
|
||||
$qmSize = $this->queue->Count();
|
||||
$qmSize --;
|
||||
//queue: 3,2,1 => pop =>2,1 => add => 2,1,3 :queue
|
||||
while($qmSize --){
|
||||
$this->queue->enqueue($this->queue->dequeue());
|
||||
}
|
||||
$val = $this->queue->dequeue();
|
||||
return $val;
|
||||
}
|
||||
|
||||
function top() {
|
||||
return $this->queue->top();
|
||||
}
|
||||
|
||||
function empty() {
|
||||
return $this->queue->isEmpty();
|
||||
}
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
@ -495,6 +495,53 @@ void myQueueFree(MyQueue* obj) {
|
||||
obj->stackOutTop = 0;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
// SplStack 类通过使用一个双向链表来提供栈的主要功能。[PHP 5 >= 5.3.0, PHP 7, PHP 8]
|
||||
// https://www.php.net/manual/zh/class.splstack.php
|
||||
class MyQueue {
|
||||
// 双栈模拟队列:In栈存储数据;Out栈辅助处理
|
||||
private $stackIn;
|
||||
private $stackOut;
|
||||
|
||||
function __construct() {
|
||||
$this->stackIn = new SplStack();
|
||||
$this->stackOut = new SplStack();
|
||||
}
|
||||
|
||||
// In: 1 2 3 <= push
|
||||
function push($x) {
|
||||
$this->stackIn->push($x);
|
||||
}
|
||||
|
||||
function pop() {
|
||||
$this->peek();
|
||||
return $this->stackOut->pop();
|
||||
}
|
||||
|
||||
function peek() {
|
||||
if($this->stackOut->isEmpty()){
|
||||
$this->shift();
|
||||
}
|
||||
return $this->stackOut->top();
|
||||
}
|
||||
|
||||
function empty() {
|
||||
return $this->stackOut->isEmpty() && $this->stackIn->isEmpty();
|
||||
}
|
||||
|
||||
// 如果Out栈为空,把In栈数据压入Out栈
|
||||
// In: 1 2 3 => pop push => 1 2 3 :Out
|
||||
private function shift(){
|
||||
while(!$this->stackIn->isEmpty()){
|
||||
$this->stackOut->push($this->stackIn->pop());
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
class MyQueue() {
|
||||
@ -533,6 +580,7 @@ class MyQueue() {
|
||||
def empty(): Boolean = {
|
||||
stackIn.isEmpty && stackOut.isEmpty
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -343,7 +343,25 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||
// 递归结束条件
|
||||
if (root == null || root == p || root == q) {
|
||||
return root
|
||||
}
|
||||
|
||||
var left = lowestCommonAncestor(root.left, p, q)
|
||||
var right = lowestCommonAncestor(root.right, p, q)
|
||||
|
||||
if (left != null && right != null) return root
|
||||
if (left == null) return right
|
||||
left
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -133,6 +133,27 @@ var moveZeroes = function(nums) {
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
```typescript
|
||||
function moveZeroes(nums: number[]): void {
|
||||
const length: number = nums.length;
|
||||
let slowIndex: number = 0,
|
||||
fastIndex: number = 0;
|
||||
while (fastIndex < length) {
|
||||
if (nums[fastIndex] !== 0) {
|
||||
nums[slowIndex++] = nums[fastIndex];
|
||||
};
|
||||
fastIndex++;
|
||||
}
|
||||
while (slowIndex < length) {
|
||||
nums[slowIndex++] = 0;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -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关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -9,7 +9,9 @@
|
||||
|
||||
# 501.二叉搜索树中的众数
|
||||
|
||||
[力扣题目链接](https://leetcode.cn/problems/find-mode-in-binary-search-tree/solution/)
|
||||
|
||||
[力扣题目链接](https://leetcode.cn/problems/find-mode-in-binary-search-tree/)
|
||||
|
||||
|
||||
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
|
||||
|
||||
@ -798,7 +800,76 @@ function findMode(root: TreeNode | null): number[] {
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
暴力:
|
||||
```scala
|
||||
object Solution {
|
||||
// 导包
|
||||
import scala.collection.mutable // 集合包
|
||||
import scala.util.control.Breaks.{break, breakable} // 流程控制包
|
||||
def findMode(root: TreeNode): Array[Int] = {
|
||||
var map = mutable.HashMap[Int, Int]() // 存储节点的值,和该值出现的次数
|
||||
def searchBST(curNode: TreeNode): Unit = {
|
||||
if (curNode == null) return
|
||||
var value = map.getOrElse(curNode.value, 0)
|
||||
map.put(curNode.value, value + 1)
|
||||
searchBST(curNode.left)
|
||||
searchBST(curNode.right)
|
||||
}
|
||||
searchBST(root) // 前序遍历把每个节点的值加入到里面
|
||||
// 将map转换为list,随后根据元组的第二个值进行排序
|
||||
val list = map.toList.sortWith((map1, map2) => {
|
||||
if (map1._2 > map2._2) true else false
|
||||
})
|
||||
var res = mutable.ArrayBuffer[Int]()
|
||||
res.append(list(0)._1) // 将第一个加入结果集
|
||||
breakable {
|
||||
for (i <- 1 until list.size) {
|
||||
// 如果值相同就加入结果集合,反之break
|
||||
if (list(i)._2 == list(0)._2) res.append(list(i)._1)
|
||||
else break
|
||||
}
|
||||
}
|
||||
res.toArray // 最终返回res的Array格式,return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
递归(利用二叉搜索树的性质):
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def findMode(root: TreeNode): Array[Int] = {
|
||||
var maxCount = 0 // 最大频率
|
||||
var count = 0 // 统计频率
|
||||
var pre: TreeNode = null
|
||||
var result = mutable.ArrayBuffer[Int]()
|
||||
|
||||
def searchBST(cur: TreeNode): Unit = {
|
||||
if (cur == null) return
|
||||
searchBST(cur.left)
|
||||
if (pre == null) count = 1 // 等于空置为1
|
||||
else if (pre.value == cur.value) count += 1 // 与上一个节点的值相同加1
|
||||
else count = 1 // 与上一个节点的值不同
|
||||
pre = cur
|
||||
|
||||
// 如果和最大值相同,则放入结果集
|
||||
if (count == maxCount) result.append(cur.value)
|
||||
|
||||
// 如果当前计数大于最大值频率,更新最大值,清空结果集
|
||||
if (count > maxCount) {
|
||||
maxCount = count
|
||||
result.clear()
|
||||
result.append(cur.value)
|
||||
}
|
||||
searchBST(cur.right)
|
||||
}
|
||||
searchBST(root)
|
||||
result.toArray // return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -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
|
||||
|
||||
|
@ -431,7 +431,84 @@ function getMinimumDifference(root: TreeNode | null): number {
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
构建二叉树的有序数组:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def getMinimumDifference(root: TreeNode): Int = {
|
||||
val arr = mutable.ArrayBuffer[Int]()
|
||||
def traversal(node: TreeNode): Unit = {
|
||||
if (node == null) return
|
||||
traversal(node.left)
|
||||
arr.append(node.value)
|
||||
traversal(node.right)
|
||||
}
|
||||
traversal(root)
|
||||
// 在有序数组上求最小差值
|
||||
var result = Int.MaxValue
|
||||
for (i <- 1 until arr.size) {
|
||||
result = math.min(result, arr(i) - arr(i - 1))
|
||||
}
|
||||
result // 返回最小差值
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
递归记录前一个节点:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def getMinimumDifference(root: TreeNode): Int = {
|
||||
var result = Int.MaxValue // 初始化为最大值
|
||||
var pre: TreeNode = null // 记录前一个节点
|
||||
|
||||
def traversal(cur: TreeNode): Unit = {
|
||||
if (cur == null) return
|
||||
traversal(cur.left)
|
||||
if (pre != null) {
|
||||
// 对比result与节点之间的差值
|
||||
result = math.min(result, cur.value - pre.value)
|
||||
}
|
||||
pre = cur
|
||||
traversal(cur.right)
|
||||
}
|
||||
|
||||
traversal(root)
|
||||
result // return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代解决:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def getMinimumDifference(root: TreeNode): Int = {
|
||||
var result = Int.MaxValue // 初始化为最大值
|
||||
var pre: TreeNode = null // 记录前一个节点
|
||||
var cur = root
|
||||
var stack = mutable.Stack[TreeNode]()
|
||||
while (cur != null || !stack.isEmpty) {
|
||||
if (cur != null) {
|
||||
stack.push(cur)
|
||||
cur = cur.left
|
||||
} else {
|
||||
cur = stack.pop()
|
||||
if (pre != null) {
|
||||
result = math.min(result, cur.value - pre.value)
|
||||
}
|
||||
pre = cur
|
||||
cur = cur.right
|
||||
}
|
||||
}
|
||||
result // return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -631,7 +631,60 @@ function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode |
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
```scala
|
||||
object Solution {
|
||||
def mergeTrees(root1: TreeNode, root2: TreeNode): TreeNode = {
|
||||
if (root1 == null) return root2 // 如果root1为空,返回root2
|
||||
if (root2 == null) return root1 // 如果root2为空,返回root1
|
||||
// 新建一个节点,值为两个节点的和
|
||||
var node = new TreeNode(root1.value + root2.value)
|
||||
// 往下递归
|
||||
node.left = mergeTrees(root1.left, root2.left)
|
||||
node.right = mergeTrees(root1.right, root2.right)
|
||||
node // 返回node,return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def mergeTrees(root1: TreeNode, root2: TreeNode): TreeNode = {
|
||||
if (root1 == null) return root2
|
||||
if (root2 == null) return root1
|
||||
var stack = mutable.Stack[TreeNode]()
|
||||
// 先放node2再放node1
|
||||
stack.push(root2)
|
||||
stack.push(root1)
|
||||
while (!stack.isEmpty) {
|
||||
var node1 = stack.pop()
|
||||
var node2 = stack.pop()
|
||||
node1.value += node2.value
|
||||
if (node1.right != null && node2.right != null) {
|
||||
stack.push(node2.right)
|
||||
stack.push(node1.right)
|
||||
} else {
|
||||
if(node1.right == null){
|
||||
node1.right = node2.right
|
||||
}
|
||||
}
|
||||
if (node1.left != null && node2.left != null) {
|
||||
stack.push(node2.left)
|
||||
stack.push(node1.left)
|
||||
} else {
|
||||
if(node1.left == null){
|
||||
node1.left = node2.left
|
||||
}
|
||||
}
|
||||
}
|
||||
root1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -476,7 +476,33 @@ func traversal(_ nums: inout [Int], _ left: Int, _ right: Int) -> TreeNode? {
|
||||
}
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def constructMaximumBinaryTree(nums: Array[Int]): TreeNode = {
|
||||
if (nums.size == 0) return null
|
||||
// 找到数组最大值
|
||||
var maxIndex = 0
|
||||
var maxValue = Int.MinValue
|
||||
for (i <- nums.indices) {
|
||||
if (nums(i) > maxValue) {
|
||||
maxIndex = i
|
||||
maxValue = nums(i)
|
||||
}
|
||||
}
|
||||
|
||||
// 构建一棵树
|
||||
var root = new TreeNode(maxValue, null, null)
|
||||
|
||||
// 递归寻找左右子树
|
||||
root.left = constructMaximumBinaryTree(nums.slice(0, maxIndex))
|
||||
root.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1, nums.length))
|
||||
|
||||
root // 返回root
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -363,7 +363,34 @@ function searchBST(root: TreeNode | null, val: number): TreeNode | null {
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
```scala
|
||||
object Solution {
|
||||
def searchBST(root: TreeNode, value: Int): TreeNode = {
|
||||
if (root == null || value == root.value) return root
|
||||
// 相当于三元表达式,在Scala中if...else有返回值
|
||||
if (value < root.value) searchBST(root.left, value) else searchBST(root.right, value)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代:
|
||||
```scala
|
||||
object Solution {
|
||||
def searchBST(root: TreeNode, value: Int): TreeNode = {
|
||||
// 因为root是不可变量,所以需要赋值给一个可变量
|
||||
var node = root
|
||||
while (node != null) {
|
||||
if (value < node.value) node = node.left
|
||||
else if (value > node.value) node = node.right
|
||||
else return node
|
||||
}
|
||||
null // 没有返回就返回空
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -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 // 最终返回根节点
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -140,6 +140,24 @@ var pivotIndex = function(nums) {
|
||||
};
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
```typescript
|
||||
function pivotIndex(nums: number[]): number {
|
||||
const length: number = nums.length;
|
||||
const sum: number = nums.reduce((a, b) => a + b);
|
||||
let leftSum: number = 0;
|
||||
for (let i = 0; i < length; i++) {
|
||||
const rightSum: number = sum - leftSum - nums[i];
|
||||
if (leftSum === rightSum) return i;
|
||||
leftSum += nums[i];
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -374,6 +374,34 @@ func removeDuplicates(_ s: String) -> String {
|
||||
return String(stack)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
PHP:
|
||||
```php
|
||||
class Solution {
|
||||
function removeDuplicates($s) {
|
||||
$stack = new SplStack();
|
||||
for($i=0;$i<strlen($s);$i++){
|
||||
if($stack->isEmpty() || $s[$i] != $stack->top()){
|
||||
$stack->push($s[$i]);
|
||||
}else{
|
||||
$stack->pop();
|
||||
}
|
||||
}
|
||||
|
||||
$result = "";
|
||||
while(!$stack->isEmpty()){
|
||||
$result.= $stack->top();
|
||||
$stack->pop();
|
||||
}
|
||||
|
||||
// 此时字符串需要反转一下
|
||||
return strrev($result);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Scala:
|
||||
```scala
|
||||
object Solution {
|
||||
@ -396,5 +424,6 @@ object Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user