1.两数之和
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
利用一个map存数组值和对{值: 索引}
如果模板值与数值某一项相减等于map中存在的值就返回map的值和当前数组索引;
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
const map = new Map();
const result = [];
for (let i = 0; i < nums.length; i++) {
// const item = nums[i];
const def = target - nums[i];
if (map.has(def)) {
result.push(map.get(def), i);
} else {
map.set(nums[i], i);
}
}
return result;
};
104. 二叉树的最大深度
使用深度优先遍历或广度优先遍历实现
DFC实现
- 节点为null返回0
- 存放左右节点递归的返回值
- 利用Math.max把最大值返回来并加上根节点 1做为返回值
var maxDepth = function (root) {
if (root === null) return 0;
const leftDeep = maxDepth(root.left);
const rightDeep = maxDepth(root.right);
return Math.max(leftDeep, rightDeep) + 1;
};
BFC
- 使用队列存放每一层节点
- 如果队列有数据则一直遍历队列内容出队并++
- while里面循环时要保存对象的最初长度再for循环遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function (root) {
if (root === null) return 0;
const queue = [root];
let deep = 0;
while (queue.length) {
let queueSize = queue.length;
for (let index = 0; index < queueSize; index++) {
const item = queue.shift();
if (item?.left) {
queue.push(item.left);
}
if (item?.right) {
queue.push(item.right);
}
}
deep++;
}
return deep;
};
102. 二叉树的层序遍历
用广度优先遍历实现
var levelOrder = function (root) {
if (root === null) return [];
const queue = [root];
const result = [];
while (queue.length) {
const queueSize = queue.length;
const valArr = [];
for (let i = 0;i < queueSize;i++) {
const item = queue.shift();
valArr.push(item.val);
item.left && queue.push(item.left);
item.right && queue.push(item.right);
}
result.push(valArr);
}
return result;
}
121. 买卖股票的最佳时机
贪心算法
var maxProfit = function (prices) {
let result = 0;
let minValue = prices[0];
for (let i = 1; i < prices.length; i++) {
result = Math.max(prices[i] - minValue, result);
minValue = Math.min(minValue, prices[i]);
}
return result;
};