链表
function ListNode(val) {
this.val = val;
this.next = null;
}
const listnode = new ListNode(1);
listnode.next = new ListNode(2);
console.log(listnode);
二叉树遍历
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
const treenode = new TreeNode(1);
console.log(treenode);
const root = {
val: "A",
left: {
val: "B",
left: {
val: "D"
},
right: {
val: "E"
}
},
right: {
val: "C",
right: {
val: "F"
}
}
};
function preorder(root) {
if (!root) return;
console.log("当前遍历的节点是:", root.val);
preorder(root.left);
preorder(root.right);
}
function inorder(root) {
if (!root) return;
preorder(root.left);
console.log("当前遍历的节点是:", root.val);
preorder(root.right);
}
function postorder(root) {
if (!root) return;
preorder(root.left);
preorder(root.right);
console.log("当前遍历的节点是:", root.val);
}
console.log("preorder:")
preorder(root);
console.log("inorder:");
inorder(root);
console.log("postorder:");
postorder(root);
Map两数求和
let map = new Map();
let arr = [1, 1, 2, 4, 8];
let target = 5;
function twoSum(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (map.has(target - arr[i])) console.log(map.get(target - arr[i]), i);
else map.set(arr[i], i);
}
}
twoSum(arr, target);
console.log(map);
合并两个有序数组
let a1 = [1, 2, 4, 8, 0, 0, 0];
let a2 = [3, 5, 7];
let l1 = 4;
let l2 = a2.length;
function merge(a1, a2, l1, l2) {
let i = l1 - 1,
j = l2 - 1,
k = l1 + l2 - 1;
while (i >= 0 && j >= 0) {
if (a1[i] > a2[j]) {
a1[k] = a1[i];
k--;
i--;
} else {
a1[k] = a2[j];
k--;
j--;
}
}
while (j >= 0) {
a1[k] = a2[j];
k--;
j--;
}
}
merge(a1, a2, l1, l2);
console.log(a1);
三数求和
let arr = [-1, 0, 1, 2, -1, -4];
let arr1 = [];
function threeSum(arr, arr1) {
arr = arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length - 2; i++) {
let j = i + 1;
let k = arr.length - 1;
if (i > 0 && arr[i] === arr[i - 1]) continue;
while (j < k) {
if (arr[i] + arr[j] + arr[k] < 0) {
j++;
while (j < k && arr[j] === arr[j - 1]) j++;
} else if (arr[i] + arr[j] + arr[k] > 0) {
k--;
while (k > j && arr[k] === arr[k + 1]) k--;
} else {
arr1.push([arr[i], arr[j], arr[k]]);
j++;
k--;
while (j < k && arr[j] === arr[j - 1]) j++;
while (k > j && arr[k] === arr[k + 1]) k--;
}
}
}
return arr1;
}
threeSum(arr, arr1);
console.log(arr1);
反转字符串及回文
let str = "abcdefg";
str = str.split("").reverse().join("");
console.log(str);
function isPalindrome1(str) {
return str === str.split("").reverse().join();
}
console.log(isPalindrome1(str));
function isPalindrome2(str) {
let len = str.length;
for (let i = 0; i < len / 2; i++)
if (str[i] !== str[len - i - 1]) return false;
return true;
}
console.log(isPalindrome2("abccba"));
function Palindrome(str) {
let len = str.length;
let i = 0,
j = len - 1;
while (str[i] === str[j]) {
i++;
j--;
}
if (isPalindrome1(str.slice(i + 1, j + 1))) return true;
if (isPalindrome1(str.slice(i, j))) return true;
return false;
}
console.log(Palindrome("abca"));