数组、链表
function quickSort (arr) {
if(arr.length <= 0) return arr;
var temp = arr[0];
var left = [];
var right = [];
for(var i = 1; i < arr.length; i++){
if(compare(temp, arr[i])){
left.push(arr[i]);
}else{
right.push(arr[i]);
}
}
return quickSort(left).concat(temp, quickSort(right));
}
function nizhi (root) {
if(root.next.next == null){
root.next.next = root;
return root.next;
}else{
var result = nizhi(root.next);
root.next.next = root;
root.next = null;
return result;
}
}
二叉树
function beforeOrder (root) {
if(root == null) return;
console.log(root.value);
beforeOrder(root.left);
beforeOrder(root.right);
}
function restoreTree1 (before, middle) {
if(before == null || middle == null || before.length == 0 || middle.length == 0 || before.length != middle.length) return null;
var root = new Node(before[0]);
var index = middle.indexOf(root.value);
var beforeLeft = before.slice(1, index + 1);
var beforeRight = before.slice(index + 1);
var middleLeft = middle.slice(0, index);
var middleRight = middle.slice(index + 1);
root.left = restoreTree1(beforeLeft, middleLeft);
root.right = restoreTree1(beforeRight, middleRight);
return root;
}
function deepSearch (root, target) {
if(root == null) return false;
if(root.value == target) return true;
var left = deepSearch(root.left, target);
var right = deepSearch(root.right, target);
return left || right;
}
function scopeSearch (rootList, target) {
if(rootList == null || rootList.length == 0) return false;
var childList = [];
for(var i = 0; i < rootList.length; i++){
if(rootList[i] != null && rootList[i].value == target){
return true;
}else{
childList.push(rootList[i].left);
childList.push(rootList[i].right);
}
}
return scopeSearch(childList, target);
}
function compareTree (root1, root2) {
if(root1 == root2) return true;
if(root1 == null && root2 != null || root1 != null && root2 == null) return false;
if(root1.value != root2.value) return false;
var left = compareTree(root1.left, root2.left);
var right = compareTree(root1.right, root2.right);
return left && right;
}
function diffTree (root1, root2, diffList) {
if(root1 == root2) return diffList;
if(root1 == null && root2 != null){
diffList.push({type: '新增', oldRoot: null, newRoot: root2});
}else if(root1 != null && root2 == null){
diffList.push({type: '删除', oldRoot: root1, newRoot: null});
}else if(root1.value != root2.value){
diffList.push({type: '修改', oldRoot: root1, newRoot: root2});
diffTree(root1.left, root2.left, diffList);
diffTree(root1.right, root2.right, diffList);
}else{
diffTree(root1.left, root2.left, diffList);
diffTree(root1.right, root2.right, diffList);
}
}
function addNode (root, num) {
if(root == null) return;
if(root.value == num) return;
if(root.value < num){
if(root.right == null) root.right = new Node(num);
else addNode(root.right, num);
}else{
if(root.left == null) root.left = new Node(num);
else addNode(root.left, num);
}
}
function buildSearchTree (arr) {
if(arr == null || arr.length == 0) return null;
var root = new Node(arr[0]);
for(var i = 0; i < arr.length; i++){
addNode(root, arr[i]);
}
return root;
}
function getDeep (root) {
if(root == null) return 0;
var leftDeep = getDeep(root.left);
var rightDeep = getDeep(root.right);
return Math.max(leftDeep, rightDeep) + 1;
}
function isBalance (root) {
if(root == null) return true;
var leftDeep = getDeep(root.left);
var rightDeep = getDeep(root.right);
if(Math.abs(leftDeep - rightDeep) > 1){
return false;
}else{
return isBalance(root.left) && isBalance(root.right);
}
}
function changeBalance (root) {
if(isBalance(root)) return root;
if(root.left != null) root.left = changeBalance(root.left);
if(root.right != null) root.right = changeBalance(root.right);
var leftDeep = getDeep(root.left);
var rightDeep = getDeep(root.right);
if(Math.abs(leftDeep - rightDeep) < 2){
return root;
}else if(leftDeep > rightDeep){
var changeTreeDeep = getDeep(root.left.right);
var noChangeTreeDeep = getDeep(root.left.left);
if(changeTreeDeep > noChangeTreeDeep){
root.left = leftRotate(root.left);
}
var newRoot = rightRotate(root);
newRoot.right = changeBalance(newRoot.right);
newRoot = changeBalance(newRoot);
return newRoot;
}else{
var changeTreeDeep = getDeep(root.right.left);
var noChangeTreeDeep = getDeep(root.right.right);
if(changeTreeDeep > noChangeTreeDeep){
root.right = rightRotate(root.right);
}
var newRoot = leftRotate(root);
newRoot.left = changeBalance(root.left);
newRoot = changeBalance(newRoot);
return newRoot;
}
}
树与图的搜索
function deepSearch (root, target) {
if(root == null) return false;
if(root.value == target) return true;
for(var i = 0; i < root.child.length; i++){
if(deepSearch(root.child[i], target)) return true;
}
return false;
}
console.log(deepSearch(A, 'G'));
function scopeSearch (roots, target) {
if(roots == null || roots.length == 0) return false;
var childList = [];
for(var i = 0; i < roots.length; i++){
if(roots[i] != null && roots[i].value == target) {
return true;
}else {
childList = childList.concat(roots[i].child);
}
}
return scopeSearch(childList, target);
}
function deepSearch (root, target, path) {
if(root == null) return false;
if(path.indexOf(root) > -1) return;
if(root.value == target) return true;
path.push(root);
for(var i = 0; i < root.neighbor.length; i++){
if(deepSearch(root.neighbor[i], target, path)) return true;
}
return false;
}
function scopeSearch (roots, target, path) {
if(roots == null || roots.length == 0) return false;
var neighborList = [];
for(var i = 0; i < roots.length; i++){
if(path.indexOf(roots[i]) > -1) continue;
path.push(roots[i]);
if(roots[i].value == target){
return true;
}else {
neighborList = neighborList.concat(roots[i].neighbor);
}
}
return scopeSearch(neighborList, target, path);
}
剑指offer
function Find(target, array){
var lenX = array.length;
var lenY = array[0].length;
for(var i = 0, j = lenY - 1; i < lenX && j >= 0;){
if(target > array[i][j]) i++;
else if(target < array[i][j]) j--;
else return true
}
return false;
}
function jumpFloorII(number){
if(number == 1) return 1;
else return 2 * jumpFloorII(number - 1);
}
function Power(base, exp){
if(base == 0){
if(exp >= 0) return 0;
else throw new Error('error');
}else{
if(exp == 0) return 1;
if(exp > 0) return power(base, exp);
else return 1 / power(base, -exp);
}
}
function power(base, exp){
if(exp == 1) return base;
if(exp % 2 == 0){
var res = power(base, exp/2);
return res * res;
}else{
return power(base, exp-1) * base;
}
}
function FindKthToTail(head, k){
var stack = [];
while(head){
stack.push(head);
head = head.next;
}
return stack[stack.length - k];
}
function Merge(pHead1, pHead2){
if(pHead1 == null || pHead2 == null) return pHead1 || pHead2;
var root = null
if(pHead1.val <= pHead2.val){
root = pHead1;
root.next = Merge(pHead1.next, pHead2);
}else{
root = pHead2;
root.next = Merge(pHead1, pHead2.next);
}
return root;
}
function HasSubtree(pRoot1, pRoot2){
if(pRoot2 == null || pRoot1 == null) return false;
return isSubtree(pRoot1,pRoot2)||
HasSubtree(pRoot1.left,pRoot2) ||
HasSubtree(pRoot1.right,pRoot2);
}
function isSubtree(pRoot1,pRoot2){
if(pRoot2 == null) return true;
if(pRoot1 == null) return false;
if(pRoot1.val == pRoot2.val){
return isSubtree(pRoot1.left,pRoot2.left) &&
isSubtree(pRoot1.right,pRoot2.right);
}else{
return false;
}
}
function Mirror(root){
if(root == null) return;
var temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
function printMatrix(matrix){
var row = matrix.length;
var col = matrix[0].length;
var result = [];
if(row == 0 || col == 0) return result;
var left = 0, right = col - 1, top = 0, bottom = row - 1;
while(left <= right && top <= bottom){
for(var i = left; i <= right; i++){
result.push(matrix[top][i]);
}
for(var i = top + 1; i <= bottom; i++){
result.push(matrix[i][right]);
}
if(top != bottom){
for(var i = right - 1; i >= left; i--){
result.push(matrix[bottom][i]);
}
}
if(left != right){
for(var i = bottom - 1; i > top; i--){
result.push(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return result;
}
function VerifySquenceOfBST(sequence){
if(!sequence.length) return false;
return BST(sequence, 0, sequence.length - 1);
}
function BST (sequence, start, end) {
if(start >= end) return true;
var i = start;
while(i < end && sequence[i++] < sequence[end]);
for(var j = i; j < end; j++){
if(sequence[j] < sequence[end]) return false;
}
return BST(sequence, start, i - 1) && BST(sequence, i, end - 1);
}
function FindPath(root, expectNumber){
var result = [];
if(root == null) return result;
getPath(root, expectNumber, result, 0, []);
return result;
}
function getPath(root, expectNum, result, curNum, path){
if(root == null) return;
curNum += root.val;
path.push(root.val);
if(curNum == expectNum && root.left == null && root.right == null){
result.push(path.slice(0));
}
getPath(root.left, expectNum, result, curNum, path);
getPath(root.right, expectNum, result, curNum, path);
path.pop();
}
function Convert(root){
if(root == null) return;
var head = null;
var realHead = null;
function getConvert(root){
if(root == null) return null;
getConvert(root.left);
if(head == null){
head = root;
realHead = root;
}else{
head.right = root;
root.left = head;
head = root;
}
getConvert(root.right);
}
getConvert(root);
return realHead;
}
function Permutation(str){
var len = str.length;
var result = [];
if(len == 0) {return [];}
if(len == 1) {result.push(str);}
else {
var obj = {};
for(var i = 0; i < len; i++){
if(!obj[str[i]]){
var temp = str[i];
var newStr = str.substring(0,i) + str.substring(i+1);
var ret = Permutation(newStr);
for(var j = 0; j < ret.length; j++){
result.push(temp + ret[j]);
}
obj[str[i]] = true;
}
}
}
return result;
}
function MoreThanHalfNum_Solution(numbers){
var len = numbers.length;
if(len == 0) return 0;
var cache = {};
numbers.forEach(function (val) {
if(cache[val]){
cache[val]++;
}else{
cache[val] = 1;
}
});
for(var p in cache){
if(cache[p] > Math.floor(len / 2)){
return p;
}
}
return 0;
}
function FindGreatestSumOfSubArray(array){
if(array.length <= 0) return 0;
var max = array[0];
var res = array[0];
for(var i = 1; i < array.length; i++){
max = Math.max(max + array[i], array[i]);
res = Math.max(max, res);
}
return res;
}
function NumberOf1Between1AndN_Solution(n){
if(n < 1) return 0;
var count = 0, num;
for(var i = 1; i <= n; i++){
num = i;
while(num > 0){
if(num % 10 == 1) count++;
num = Math.floor(num / 10);
}
}
return count;
}
function PrintMinNumber(numbers){
var result = '';
numbers.sort(function (a, b) {
var str1 = '' + a + b;
var str2 = '' + b + a;
for(var i = 0; i < str1.length; i++){
if(str1.charAt(i) > str2.charAt(i)){
return 1;
}
if(str1.charAt(i) < str2.charAt(i)){
return -1;
}
}
return -1;
});
for(var i = 0; i < numbers.length; i++){
result += numbers[i];
}
return result;
}
function GetUglyNumber_Solution(index){
if(index <= 0) return 0;
var uglyNum = [1];
var num2 = 0,
num3 = 0,
num5 = 0;
for(var i = 1; i < index; i++){
uglyNum[i] = Math.min(uglyNum[num2] * 2, uglyNum[num3] * 3, uglyNum[num5] * 5);
if(uglyNum[i] == uglyNum[num2] * 2) num2++;
if(uglyNum[i] == uglyNum[num3] * 3) num3++;
if(uglyNum[i] == uglyNum[num5] * 5) num5++;
}
return uglyNum[index - 1];
}
function FirstNotRepeatingChar(str){
for(var i = 0; i < str.length; i++){
if(str.indexOf(str[i]) == str.lastIndexOf(str[i])){
return i;
break;
}
}
return -1;
}
function InversePairs(data){
if(!data || data.length < 2) return 0;
var sum = 0;
var copy = data.slice();
sum = findReverse(data, copy, 0, data.length - 1);
return (sum % 1000000007);
}
function findReverse(data, copy, start, end){
if(start == end) return 0;
var mid = parseInt((end - start) / 2);
var left = findReverse(copy, data, start, start + mid);
var right = findReverse(copy, data, start + mid + 1, end);
var count = 0;
var i = start + mid;
var j = end;
var index = end;
while(i >= start && j >= start + mid + 1){
if(data[i] > data[j]){
count += j - start - mid;
copy[index--] = data[i--];
}else{
copy[index--] = data[j--];
}
}
while(i >= start){
copy[index--] = data[i--];
}
while(j >= start + mid + 1){
copy[index--] = data[j--];
}
return left + count + right;
}
function FindFirstCommonNode(pHead1, pHead2){
var p1 = pHead1;
var p2 = pHead2;
while(p1 != p2){
p1 = p1 == null ? pHead2 : p1.next;
p2 = p2 == null ? pHead1 : p2.next;
}
return p1;
}
function FindContinuousSequence(sum){
if(sum < 2) return [];
var result = [];
var temp = [];
var start = 1;
var num = 0;
var end = Math.ceil(sum / 2);
while(start <= end){
num += end;
temp.unshift(end);
if(num == sum){
result.unshift(temp.slice());
num = num - temp.pop();
}
else if(num > sum){
num = num - temp.pop();
}
end--;
}
return result;
}
function FindNumbersWithSum(array, sum){
var result = [];
var index;
for(var i = 0; i < array.length - 1; i++){
index = array.indexOf(sum - array[i], i + 1);
if(index != -1) return [array[i], array[index]]
}
return result;
}
function IsContinuous(numbers){
var len = numbers.length;
if(len != 5) return false;
var temp = [];
for(var i = 0; i < 14; i++){
temp.push(0);
}
var min = 14,
max = -1;
for(var i = 0; i < len; i++){
temp[numbers[i]]++;
if(numbers[i] == 0) continue;
if(temp[numbers[i]] > 1) return false;
if(numbers[i] > max) max = numbers[i];
if(numbers[i] < min) min = numbers[i];
}
return max - min < 5
}
function LastRemaining_Solution(n, m){
if(n < 1) return -1;
if(n == 1) return 0;
return (LastRemaining_Solution(n - 1, m) + m) % n;
}
function multiply(array){
if(array == null || array.length == 0) return [];
var result = [];
var tempArr, temp;
for(var i = 0; i < array.length; i++){
tempArr = array.filter(function (e, index) {
return index != i;
});
temp = 1;
tempArr.map(function (e, index) {
temp *= e;
});
result[i] = temp;
}
return result;
}
function isNumeric(s){
var reg = /[+-]?\d*(\.\d*)?([eE][+-]?\d+)?/g;
return s.match(reg)[0] == s;
}
function EntryNodeOfLoop(pHead){
if(pHead == null || pHead.next == null || pHead.next.next == null) return null;
var p1 = pHead;
var p2 = pHead;
while(true){
p1 = p1.next;
p2 = p2.next.next;
if(p1 == p2) break;
}
p1 = pHead;
while(true){
if(p1 == p2) return p1;
else{
p1 = p1.next;
p2 = p2.next;
}
}
}
function deleteDuplication(pHead){
var newHead = new ListNode('head');
newHead.next = pHead;
var pHead = newHead;
var qHead = pHead.next;
while(qHead){
while((qHead.next != null) && (qHead.val == qHead.next.val)){
qHead = qHead.next;
}
if(pHead.next == qHead){
pHead = qHead;
qHead = qHead.next;
}
else{
qHead = qHead.next;
pHead.next = qHead;
}
}
return newHead.next;
}
function GetNext(pNode){
if (!pNode) return null;
if (pNode.right) {
pNode = pNode.right
while(pNode.left){
pNode = pNode.left
}
} else {
while (pNode) {
if (!pNode.next) return null;
if (pNode.next.left === pNode) return pNode.next;
pNode = pNode.next;
}
}
return pNode;
}
function isSymmetrical(pRoot){
if(pRoot == null) return true;
return getSymmetrical(pRoot.left, pRoot.right);
}
function getSymmetrical (rootLeft, rootRight){
if(rootLeft == null) return rootRight == null;
if(rootRight == null) return false;
if(rootLeft.val != rootRight.val) return false;
return getSymmetrical(rootLeft.left, rootRight.right) && getSymmetrical(rootLeft.right, rootRight.left);
}
function Print(pRoot){
if(!pRoot) return [];
var stack = [];
var result = [];
var flag = true;
stack.push(pRoot);
var len, tempArr;
while(stack.length){
len = stack.length;
tempArr = [];
for(var i = 0; i < len; i++){
var temp = stack.shift();
tempArr.push(temp.val);
if(temp.left) stack.push(temp.left);
if(temp.right) stack.push(temp.right);
}
if(!flag) tempArr.reverse();
flag = !flag;
result.push(tempArr);
}
return result;
}
function KthNode(root, k){
if(k <= 0 || !root) return;
var tempArr = [];
getNode(root, tempArr);
return tempArr[k - 1];
}
function getNode (root, res) {
if(!root) return;
getNode(root.left, res);
res.push(root);
getNode(root.right, res);
}
var arr = [];
function Insert(num)
{
if(arr.length == 0) arr.push(num);
else{
var len = arr.length;
while(len >= 0 && num < arr[len - 1]){
arr[len] = arr[len - 1];
len--;
}
arr[len] = num;
}
}
function GetMedian(){
var len = arr.length;
odd = len % 2 == 1;
index = Math.ceil(len / 2);
if(odd){
return arr[index - 1];
}else{
return (arr[index] + arr[index - 1]) / 2;
}
}
function maxInWindows(num, size){
if(size <= 0) return [];
var tempArr;
var result = [];
var start = 0;
var end = num.length - size;
for(var i = 0; i <= end; i++){
tempArr = num.slice(i, i + size);
result.push(Math.max(...tempArr));
}
return result;
}
function hasPath(matrix, rows, cols, path){
if(!rows || !cols || rows * cols < path.length) return false;
for(var i = 0; i < rows; i++){
for(var j = 0; j < cols; j++){
if(getPath(matrix, i, j, rows, cols, path, 0, [])) return true;
}
}
return false;
}
function getPath (matrix, i, j, rows, cols, path, k, flag){
var index = i * cols + j;
if(i < 0 || j < 0 || i >= rows || j >= cols || matrix[index] != path[k] || flag[index] == true) return false;
if(k == path.length -1 ) return true;
flag[index] = true;
if(getPath(matrix, i - 1, j, rows, cols, path, k + 1, flag) ||
getPath(matrix, i + 1, j, rows, cols, path, k + 1, flag) ||
getPath(matrix, i, j - 1, rows, cols, path, k + 1, flag) ||
getPath(matrix, i, j + 1, rows, cols, path, k + 1, flag)
) return true;
flag[index] = false;
return false;
}
function movingCount(threshold, rows, cols){
var flag = [];
for(var i = 0; i < rows; i++){
flag.push([]);
for(var j = 0; j < cols; j++){
flag[i][j] = false;
}
}
return moveCount(threshold, rows, cols, 0, 0, flag);
}
function moveCount (threshold, rows, cols, i, j, flag) {
if(i < 0 || j < 0 || i >= rows || j >= cols || flag[i][j] || sum(i, j) > threshold) return 0;
flag[i][j] = true;
return moveCount(threshold, rows, cols, i - 1, j, flag) +
moveCount(threshold, rows, cols, i + 1, j, flag) +
moveCount(threshold, rows, cols, i, j - 1, flag) +
moveCount(threshold, rows, cols, i, j + 1, flag) + 1;
}
function sum(i, j) {
var sum = 0;
var temp = '' + i + j;
for(var i = 0; i < temp.length; i++){
sum += +(temp[i]);
}
return sum;
}
function cutRope(number){
var ans = [0, 0, 1, 2, 4];
var result = [];
if(number < 5) return ans[number];
while(number > 0){
if(number - 3 >= 0){
result.push(3);
number -= 3;
}
if(number - 2 >= 0){
result.push(2);
number -= 2;
}
}
return result.reduce((m, n) => m * n);
}
总结难题
function LCS2 (str1, str2) {
var cache = [];
var tempCache;
function _lcs (str1, str2) {
if(!str1 || !str2) return '';
for(var i = 0; i < cache.length; i++){
if(cache[i].str1 == str1 && cache[i].str2 == str2) return cache[i].result;
}
if(str1[0] == str2[0]){
tempCache = str1[0] + _lcs(str1.substr(1), str2.substr(1));
}else{
var s1 = _lcs(str1, str2.substr(1));
var s2 = _lcs(str1.substr(1), str2);
tempCache = s1.length > s2.length ? s1 : s2;
}
cache.push({
str1: str1,
str2, str2,
result: tempCache
});
return tempCache;
}
return _lcs(str1, str2);
}