本文爲8月牛客網《劍指 offer》刷題作得,現整理出來做爲參考。
雖然是算法題,但本文用 JavaScript 編寫,看了《劍指 offer》之後發現不少問題處理的過程並非最好的,因此本文僅供參考。之前所有代碼 AC 經過,但即使是 AC 的代碼也不見得就是最好的,好比有的內存分配了卻沒有釋放,這樣的問題牛客網是查不出來的。node
function Find(target, array){ var rowCount = array.length - 1, i, j; for(i=rowCount,j=0; i >= 0 && j < array[i].length;){ if(target == array[i][j]){ return true; }else if(target > array[i][j]){ j++; continue; }else if(target < array[i][j]){ i--; continue; } } return false; }
function replaceSpace(str){ return str.replace(/ /g, '%20'); }
/*function ListNode(x){ this.val = x; this.next = null; }*/ function printListFromTailToHead(head){ if(!head){ return 0; } else { var arr = new Array(); var curr = head; while(curr){ arr.push(curr.val); curr = curr.next; } return arr.reverse(); } }
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function reConstructBinaryTree(pre, vin){ if(pre.length == 0 || vin.length == 0){ return null; }; var index = vin.indexOf(pre[0]); var left = vin.slice(0,index); var right = vin.slice(index+1); var node = new TreeNode(vin[index]); node.left = reConstructBinaryTree(pre.slice(1,index+1),left); node.right = reConstructBinaryTree(pre.slice(index+1),right); return node; }
var stack1 = []; var stack2 = []; function push(node){ stack1.push(node); } function pop(){ var temp = stack1.pop(); while(temp){ stack2.push(temp); temp = stack1.pop(); } var result = stack2.pop(); temp = stack2.pop(); while(temp){ stack1.push(temp); temp = stack2.pop(); } return result; }
function minNumberInRotateArray(rotateArray){ var len = rotateArray.length; if(len === 0){ return 0; } return Math.min.apply(null,rotateArray); }
function Fibonacci(n){ var a = 1, b = 1, temp; if(n <= 0) return 0; for(var i = 2; i <= n; i++){ temp = b; b = a + b; a = temp; } return a; }
function jumpFloor(number){ if(number < 1){ return 0; } if(number === 1){ return 1; } if(number === 2){ return 2; } var temp = 0, a = 1, b = 2; for(var i = 3; i <= number; i++){ temp = a + b; a = b; b = temp; } return temp; }
function jumpFloorII(number){ return Math.pow(2, number - 1); }
function rectCover(number){ var a = 1, b = 2, temp; if(number <= 0){ return 0; } if(number === 1){ return 1; } if(number === 2){ return 2 } for(var i = 3; i <= number; i++){ temp = a + b; a = b; b = temp; } return temp; }
function NumberOf1(n){ if(n < 0){ n = n >>> 0; } var arr = n.toString(2).split(''); return arr.reduce(function(a,b){ return b === "1" ? a + 1 : a; },0); }
function Power(base, exponent){ return Math.pow(base, exponent); }
function reOrderArray(array){ var result = []; var even = []; array.forEach(function(item){ if((item & 1) === 1){ result.push(item); } else { even.push(item); } }); return result.concat(even); }
/*function ListNode(x){ this.val = x; this.next = null; }*/ function FindKthToTail(head, k){ if(!head || k <= 0){ return null; } var i = head, j = head; while(--k){ j = j.next; if(!j){ return null; } } while(j.next){ i = i.next; j = j.next; } j = null; return i; }
/*function ListNode(x){ this.val = x; this.next = null; }*/ function ReverseList(pHead){ var newHead, temp; if(!pHead){ return null; } if(pHead.next === null){ return pHead; } else { newHead = ReverseList(pHead.next); } temp = pHead.next; temp.next = pHead; pHead.next = null; temp = null; return newHead; }
/*function ListNode(x){ this.val = x; this.next = null; }*/ function Merge(pHead1, pHead2){ if(!pHead1){ return pHead2 ? pHead2 : null } else if(!pHead2){ return pHead1; } // debugger; var curr1 = pHead1; var curr2 = pHead2; var result = new ListNode(-1); var curr = result; while(curr1 && curr2){ if(curr1.val < curr2.val){ curr.next = curr1; curr1 = curr1.next; } else{ curr.next = curr2; curr2 = curr2.next; } curr = curr.next; } if(curr1){ curr.next = curr1; } if(curr2){ curr.next = curr2; } //防止內存泄露 curr = result.next; result.next = null; result = curr; curr = curr1 = curr2 = null; return result; }
function HasSubtree(pRoot1, pRoot2){ if(pRoot1 == null || pRoot2 == null){ return false; } if(isSubTree(pRoot1, pRoot2)){ return true; } else{ return 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){ return null; } var temp = root.left; root.left = root.right; root.right = temp; if(root.left){ Mirror(root.left); } if(root.right){ Mirror(root.right); } }
function printMatrix(matrix){ if(!matrix || !matrix.length) return null; var result = []; var rows = matrix.length, cols = matrix[0].length; var len = rows * cols; var i = 0, j = 0; var circle = 0; while(1){ while(j < cols - circle){ result.push(matrix[i][j]); j++; } if(result.length === len) break; j--, i++; while(i < rows - circle){ result.push(matrix[i][j]) i++; } if(result.length === len) break; i--, j--; while(j >= circle){ result.push(matrix[i][j]); j--; } if(result.length === len) break; j++, i--; circle++; while(i >= circle){ result.push(matrix[i][j]) i--; } if(result.length === len) break; j++, i++; } return result; }
var stack = []; function push(node){ stack.push(node); } function pop(){ return stack.pop(); } function top(){ return stack[stack.length - 1]; } function min(){ return Math.min.apply(null, stack); }
function IsPopOrder(pushV, popV){ if(!pushV.length || !popV.length){ return false; } var temp = []; var popIndex = 0; var len = pushV.length; for(var i = 0; i < len; i++){ temp.push(pushV[i]); while(temp.length && temp[temp.length - 1] === popV[popIndex]){ temp.pop(); popIndex++; } } return temp.length === 0; }
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function PrintFromTopToBottom(root){ if (!root) { return []; } var queue = []; queue.push(root); var result = []; while (queue.length) { var temp = queue.shift(); result.push(temp.val); if (temp.left) { queue.push(temp.left); } if (temp.right) { queue.push(temp.right); } } return result; }
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function VerifySquenceOfBST(sequence) { var len = sequence.length if (!len) { return false; } return adjustSequence(0, len - 1); function adjustSequence(start, end){ if (start >= end) { return true; } var root = sequence[end]; for(var i = start; i < end && sequence[i] < root; i++); var index = i; for (i = i + 1; i < end; i++) { if (sequence[i] < root) { return false; } } return adjustSequence(start, index - 1) && (adjustSequence(index, end - 1)); } }
/* function TreeNode(x) { this.val = x; this.left = null; this.right = null; } */ function FindPath(root, expectNumber){ var temp = []; // var found = false; var result = []; dfs(root, 0); return result; function dfs(root, sum){ // debugger;s if(!root){ return; } temp.push(root.val); sum += root.val; if(!root.left && !root.right && sum === expectNumber){ result.push(temp.concat()); } if(root.left){ dfs(root.left, sum); } if(root.right){ dfs(root.right, sum); } temp.pop(); return; } }
function Clone(pHead) { if(!pHead){ return null; } var head = new RandomListNode(pHead.label); head.random = pHead.random; head.next = Clone(pHead.next); return head; }
將左子樹構成雙向鏈表,返回的是左子樹的尾結點,將其鏈接到root的左邊;
將右子樹構成雙向鏈表,將其追加到root結點以後,並返回尾結點;
向左遍歷返回的鏈表至頭結點處,即爲所求雙向鏈表的首結點。
function Convert(pRootOfTree){ if(!pRootOfTree) { return null; } var lastNode = null; lastNode = ConvertNode(pRootOfTree); var head = lastNode; while(head && head.left) { head = head.left; } return head; function ConvertNode(node){ if(!node){ return; } if(node.left) { lastNode = ConvertNode(node.left); } node.left = lastNode; if(lastNode){ lastNode.right = node; } lastNode = node; if(node.right){ lastNode = ConvertNode(node.right); } return lastNode; } }
function Permutation(str){ if(!str || str.length === 0){ return []; } var result = []; var arr = str.split(''); var temp = ''; ordering(arr); result = result.filter(function(item, index){ //去重 return result.indexOf(item) === index; }); return result; function ordering(tempArr){ if(tempArr.length === 0){ result.push(temp); return; } for(var i = 0; i < tempArr.length; i++){ temp += tempArr[i]; insideArr = tempArr.concat(); insideArr.splice(i,1); ordering(insideArr); temp = temp.substring(0, temp.length - 1); //回溯 } } }
function MoreThanHalfNum_Solution(numbers){ if(!numbers || numbers.length === 0){ return 0; } var arr = []; var len = numbers.length, index; for(var i = 0; i < len; i++){ var index = numbers[i]; arr[index] !== undefined ? arr[index]++ : arr[index] = 1; } var index = -1; var arrLen = arr.length; var max = -Infinity; for(var i = 0; i < arrLen; i++){ if(!arr[i]) continue; max = arr[i] > max ? (index = i, arr[i]) : max; } return max > len / 2 ? index : 0; }
function GetLeastNumbers_Solution(input, k){ if(!input || input.length < k){ return []; } return input.sort(function(a,b){ return a - b }).slice(0, k); }
function FindGreatestSumOfSubArray(array){ if (array.length < 0) return 0; var sum = array[0], tempsum = array[0]; for (var i = 1; i < array.length; i++) { tempsum = tempsum < 0 ? array[i] : tempsum + array[i]; sum = tempsum > sum ? tempsum : sum; } return sum; }
function NumberOf1Between1AndN_Solution(n) { if (n < 0) return 0; var ones = 0; var arr = []; while(n){ arr.push(n); n--; } return arr.join('').replace(/[^1]+/g,'').length; }
function PrintMinNumber(numbers) { if(!numbers || numbers.length === 0){ return []; } var result = []; var temp = ''; ordering(numbers); result = result.map(Number).reduce(function(min , a){ //最小值 return min < a ? min : a; }, Infinity); return result; function ordering(tempArr){ var innerLen = 0; if(tempArr.length === 0){ result.push(temp); return; } for(var i = 0; i < tempArr.length; i++){ innerLen = tempArr[i].toString().length; temp += tempArr[i]; insideArr = tempArr.concat(); insideArr.splice(i,1); ordering(insideArr); temp = temp.substring(0, temp.length - innerLen); //回溯 } } }
function GetUglyNumber_Solution(index) { if (index === 0) return 0; var uglyNum = [1]; var factor2 = 0, factor3 = 0, factor5 = 0; for (var i = 1; i < index; i++) { uglyNum[i] = Math.min(uglyNum[factor2] * 2, uglyNum[factor3] * 3, uglyNum[factor5] * 5); if (uglyNum[i] === uglyNum[factor2] * 2) factor2++; if (uglyNum[i] === uglyNum[factor3] * 3) factor3++; if (uglyNum[i] === uglyNum[factor5] * 5) factor5++; } return uglyNum[index - 1]; }
function FirstNotRepeatingChar(str){ if(!str || !str.length){ return -1; } var hash = {}; var tempArr = str.split(''); var unique = []; var len = str.length, temp; for(var i = 0; i < len; i++){ temp = tempArr[i]; if(hash[temp]){ hash[temp].push(i); } else { hash[temp] = [i]; } } for(var key in hash){ if(hash.hasOwnProperty(key)){ if(hash[key].length === 1){ unique.push(hash[key].pop()); } } } return Math.min.apply(null, unique); }
因爲時間空間複雜度的限制,js 貌似沒法完成這個題,因此使用 c++ 完成。
class Solution { public: long long InversePairsCore(vector<int> &data, vector<int>©, int start, int end){ if(start == end){ copy[start] = data[start]; return 0; } int length = (end - start) / 2; long long left = InversePairsCore(copy, data, start, start + length); long long right = InversePairsCore(copy, data, start + length + 1, end); int i = start + length; int j = end; int indexCopy = end; long long count=0; while(i >= start && j >= start + length + 1){ if(data[i] > data[j]){ copy[indexCopy--] = data[i--]; count += j - start - length; } else { copy[indexCopy--] = data[j--]; } } for(; i >= start; --i) copy[indexCopy--] = data[i]; for(;j >= start + length + 1; --j) copy[indexCopy--] = data[j]; return left + right + count; } int InversePairs(vector<int> data) { int length = data.size(); if(length <= 0) return 0; vector<int> copy; for(int i = 0; i < length; i++) copy.push_back(data[i]); long long count = InversePairsCore(data, copy, 0, length-1); copy.clear(); return count % 1000000007; } };
function FindFirstCommonNode(pHead1, pHead2){ if(!pHead1 || !pHead2){ return null; } var len1 = getLength(pHead1); var len2 = getLength(pHead2); var lenDiff = len1 - len2; var curr1 = pHead1; var curr2 = pHead2; if(len2 > len1){ curr1 = pHead2; curr2 = pHead1; lenDiff = len2 - len1; } for(var i = 0; i < lenDiff; ++i) curr1 = curr1.next; while(curr1 && curr2 && curr1 != curr2){ curr1 = curr1.next; curr2 = curr2.next; } return curr1; function getLength(node){ var len = 0; curr = node; while(curr){ len++; curr = curr.next; } return len; } }
function GetNumberOfK(data, k){ return data.reduce(function(count, a){ return a === k ? count+1 :count; }, 0); }
function TreeDepth(pRoot){ if(!pRoot){ return 0; } var depth = 0; var currDepth = 0; dfs(pRoot); return depth; function dfs(node){ if(!node){ depth = depth > currDepth ? depth : currDepth; return; } currDepth++; dfs(node.left); dfs(node.right); currDepth--; } }
function IsBalanced_Solution(pRoot){ if(!pRoot){ return true; } var left = TreeDepth(pRoot.left); var right = TreeDepth(pRoot.right); var diff = left - right; if(diff > 1 || diff < -1) return false; return IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right); function TreeDepth(pRoot){ if(!pRoot){ return 0; } var depth = 0; var currDepth = 0; dfs(pRoot); return depth; function dfs(node){ if(!node){ depth = depth > currDepth ? depth : currDepth; return; } currDepth++; dfs(node.left); dfs(node.right); currDepth--; } } }
function FindNumsAppearOnce(array){ if (!array || array.length < 2) return []; return array.sort().join(',').replace(/(\d+),\1/g,"").replace(/,+/g,',').replace(/^,|,$/, '').split(',').map(Number); }
function FindContinuousSequence(sum){ if(sum < 3){ return []; } var small = 1, big = 2; var mid = (1 + sum) / 2; var curr = small + big; var result = []; while(small < mid){ if(curr === sum){ pushSeq(small, big); } while(curr > sum && small < mid){ curr -= small; small++; if(curr === sum){ pushSeq(small, big); } } big++; curr += big; } result.sort(function(a,b){return a[0] - b[0];}); return result; function pushSeq(small, big){ var temp = []; for(var i = small; i <= big; i++){ temp.push(i); } result.push(temp); } }
function FindNumbersWithSum(array, sum){ if(!array || !array.length){ return []; } var result = []; var product = []; var head = 0, tail = array.length - 1; while(head < tail){ var curr = array[head] + array[tail]; if(curr === sum){ result.push([array[head], array[tail]]); product.push(array[head] * array[tail]); tail--; head++; } else if(curr > sum){ tail--; } else { head++; } } if(result.length === 0){ return []; } var min = Math.min.apply(null, product); var index = product.indexOf(min); return result[index]; }
function LeftRotateString(str, n){ if(!str){ return ""; } var len = str.length; n = n % len; var left = str.slice(0,n); var right = str.slice(n); return right + left; }
function ReverseSentence(str){ return str.split(' ').reverse().join(' '); }
function IsContinuous(numbers){ if(!numbers || numbers.length < 1){ return false; } var len = numbers.length; numbers.sort(function(a,b){return a - b;}); var zeros = 0, gaps = 0; for(var i = 0; i < len && numbers[i] == 0; i++){ zeros++; } var small = zeros, big = small + 1; while(big < len){ if(numbers[small] == numbers[big]){ return false; } gaps += numbers[big] - numbers[small] - 1; small = big++; } return gaps <= zeros; }
function LastRemaining_Solution(n, m){ if(n < 1 || m < 1){ return -1; } var last = 0; for(var i = 2; i <= n; i++){ last = (last + m) % i; } return last; }
function Sum_Solution(n){ var sum = 0; plus(n); return sum; function plus(num){ sum += num; num > 0 && plus(--num); } }
function Add(num1, num2){ var sum, carry; do{ sum = num1 ^ num2; carry = (num1 & num2) << 1; num1 = sum; num2 = carry; }while(num2 != 0); return num1; }
function StrToInt(str){ if(str.length === 0){ return 0; } var format = str.match(/^(\+?|-?)(\d+)$/); if(!format){ return 0; } var num = 0; var temp = format[2]; var base = 1; var flag = format[1]; for(var i = temp.length - 1; i >= 0; i--){ num += parseInt(temp[i]) * base; base *= 10; } return flag === '-' ? num * (-1) : num; }
function duplicate(numbers, duplication){ if(!numbers || !numbers.length){ return false; } var len = numbers.length; for(var i = 0; i < len; i++){ var curr = numbers[i]; if(numbers.indexOf(curr) !== i){ duplication[0] = curr; return true; } } return false; }
function multiply(array){ if(!array || !array.length){ return []; } var result = []; var len1 = array.length, len2 = result.length; result[0] = 1; for(var i = 1; i < len1; i++){ result[i] = array[i - 1] * result[i - 1]; } var temp = 1; for(var i = len1 - 2; i >= 0;--i){ temp *=array[i + 1]; result[i] *= temp } return result; }
function match(s, pattern) { if(s === "" && pattern === ""){ return true; } if(!pattern || pattern.length === 0){ return false } var reg = new RegExp('^' + pattern + '$'); return reg.test(s); }
function isNumeric(s){ var reg = /^[+-]?(?:(\d+)(\.\d+)?|(\.\d+))([eE][+-]?\d+)?$/; return reg.test(s); }
function Init(){ streamNums = []; //定義一個全局變量, 不用var streamNumsLen = 256; //定義一個全局變量, 不用var streamNumsIndex = 0; //定義一個全局變量, 不用var for(var i = 0; i < streamNumsLen; i++){ streamNums[i] = -1; } } function Insert(ch){ var code = ch.charCodeAt(); if(streamNums[code] == -1){ streamNums[code] = streamNumsIndex; } else if(streamNums[code] >= 0){ streamNums[code] = -2; } streamNumsIndex++; } function FirstAppearingOnce(){ result = ''; var ch = ''; var minIndex = Infinity; for(var i = 0; i < streamNumsLen; i++){ if(streamNums[i] >= 0 && streamNums[i] < minIndex){ ch = String.fromCharCode(i); minIndex = streamNums[i]; } } return ch == "" ? '#' : ch; }
/*function ListNode(x){ this.val = x; this.next = null; }*/ function EntryNodeOfLoop(pHead){ if(!pHead){ return null; } var meeting = meetingNode(pHead); if(!meeting){ return null; } var nodeLoop = 1; var node1 = meeting; while(node1.next != meeting){ node1 = node1.next; nodeLoop++; } node1 = pHead; for(var i = 0; i < nodeLoop; i++){ node1 = node1.next; } var node2 = pHead; while(node1 != node2){ node1 = node1.next; node2 = node2.next; } return node1; function meetingNode(node){ if(!node || !node.next){ return null; } var slow = node.next; var fast = slow.next; while(fast && slow){ if(fast === slow){ return fast; } slow = slow.next; fast = fast.next; if(fast){ fast = fast.next; } } return null; } }
function deleteDuplication(pHead){ if(!pHead){ return null; } var tempHead = new ListNode(-1); tempHead.next = pHead; var preNode = tempHead; var curr1 = preNode.next; var curr2 = curr1.next; while(curr1){ if(!curr2 || curr2.val !== curr1.val){ if(curr1.next !== curr2){ clear(curr1, curr2); preNode.next = curr2; } else { preNode = curr1; } curr1 = curr2; if(curr2){ curr2 = curr2.next; } } else { if(curr2){ curr2 = curr2.next; } } } return tempHead.next; function clear(node, stop){ var temp; while(node !== stop){ temp = node.next; node.next = null; node = temp; } } }
function GetNext(pNode){ if (!pNode){ return pNode; } if (pNode.right){ pNode = pNode.right; while (pNode.left) { pNode = pNode.left; } return pNode; } else if(pNode.next && pNode.next.left == pNode){ return pNode.next; } else if(pNode.next && pNode.next.right == pNode){ while(pNode.next && pNode.next.left != pNode){ pNode = pNode.next ; } return pNode.next; } else { return pNode.next; } }
function isSymmetrical(pRoot){ if(!pRoot){ return true; } return symmetrical(pRoot, pRoot); function symmetrical(node1,node2){ if(!node1 && !node2) return true; if(!node1 || !node2) return false; if(node1.val != node2.val) return false; return symmetrical(node1.left, node2.right) && symmetrical(node1.right, node2.left); } }
function Print(pRoot) { var res = []; if(!pRoot){ return res; } var que = []; que.push(pRoot); var flag = false; while(que.length > 0){ var vec = []; var len = que.length; for(var i = 0; i < len; i++){ var tmp = que.shift(); //front vec.push(tmp.val); if(tmp.left) que.push(tmp.left); if(tmp.right) que.push(tmp.right); } if(flag){ vec.reverse(); } res.push(vec); flag = !flag; } return res; }
function Print(pRoot) { var res = []; if(!pRoot){ return res; } var que = []; que.push(pRoot); while(que.length > 0){ var vec = []; var len = que.length; for(var i = 0; i < len; i++){ var tmp = que.shift(); //front vec.push(tmp.val); if(tmp.left) que.push(tmp.left); if(tmp.right) que.push(tmp.right); } res.push(vec); } return res; }
function Serialize(pNode) { var str = []; ser(pNode); for(var i = str.length - 1; i >= 0; i--){ if(str[i] !== '#'){ break; } str.pop(); } return str.join(); function ser(node){ if(!node){ str.push('#'); return; } str.push(node.val); ser(node.left); ser(node.right); } } function Deserialize(str) { var index = -1; var len = str.length; if(index >= len){ return null; } var arr = str.split(","); var head = des(); return head; function des(node){ index++; if(arr[index] && arr[index] !== '#'){ var temp = new TreeNode(arr[index]); node = temp; node.left = des(); node.right = des(); } return node; } }
function KthNode(pRoot, k){ if(!pRoot || !k){ return null; } return KthCore(pRoot); function KthCore(node){ var target = null; if(node.left){ target = KthCore(node.left); } if(!target){ if(k === 1) target = node; k--; } if(!target && node.right) target = KthCore(node.right); return target; } }
var arr = []; function Insert(num){ arr.push(num); arr.sort(function(a,b){ return a - b; }); return arr; } function GetMedian(){ var mid = Math.floor(arr.length / 2); if((arr.length & 1) === 0){ var n1 = arr[mid]; var n2 = arr[mid - 1]; return (n1 + n2) / 2; } else { return arr[mid] } }
function maxInWindows(num, size){ if(!num || num.length === 0){ return null; } var max = []; if(num.length >= size && size >= 1){ var index = []; for(var i = 0; i < size; ++i){ while(index.length > 0 && num[i] >= num[index[index.length - 1]]) index.pop(); index.push(i); } for(var i = size; i < num.length; ++i){ max.push(num[index[0]]); while(index.length > 0 && num[i] >= num[index[index.length - 1]]) index.pop(); if(index.length > 0 && index[0] <= i - size) index.shift(); index.push(i); } max.push(num[index[0]]); } return max; }
function hasPath(matrix, rows, cols, path){ var visited = []; for(var i = 0; i < rows * cols; i++){ visited[i] = false; } var pathLen = 0; try{ for(var i = 0; i < rows; i++){ for(var j = 0; j < cols; j++){ if(core(i,j)){ return true; } } } } finally { visited.length = 0; } return false; function core(row, col){ if(path.length === pathLen){ return true; } var hasPath = false; if(row >= 0 && row < rows && col >= 0 && col < cols && matrix[row * cols + col] === path[pathLen] && !visited[row * cols + col]){ pathLen++; visited[row * cols + col] = true; hasPath = core(row - 1, col)+ core(row, col - 1) + core(row + 1, col) + core(row, col + 1); if(!hasPath){ pathLen--; visited[row * cols + col] = false; } } return hasPath; } }
function movingCount(threshold, rows, cols){ var visited = []; for(var i = 0; i < rows * cols; ++i) visited[i] = false; var count = movingCountCore(0, 0); visited.length = 0; return count; function getDigitSum(number){ var sum = 0; while(number > 0){ sum += number % 10; number = Math.floor(number / 10); } return sum; } function check(row, col){ if(row >= 0 && row < rows && col >= 0 && col < cols && getDigitSum(row) + getDigitSum(col) <= threshold && !visited[row * cols + col]) return true; return false; } function movingCountCore(row, col){ var count = 0; if(check(row, col)) { visited[row * cols + col] = true; count = 1 + movingCountCore(row - 1, col) + movingCountCore(row, col - 1) + movingCountCore(row + 1, col) + movingCountCore(row, col + 1); } return count; } }
function TreeNode(x) { this.val = x; this.left = null; this.right = null; } function Tree(arr, node, num = 1){ if(!arr || arr.length === 0){ return new TreeNode(null); } node = node || new TreeNode(arr[num - 1]); var curr = node; if(num * 2 - 1 < arr.length && arr[num * 2 - 1]){ curr.left = new TreeNode(arr[num * 2 - 1]); Tree(arr, curr.left, num * 2); } if(num * 2 < arr.length && arr[num * 2]){ curr.right = new TreeNode(arr[num * 2]); Tree(arr, curr.right, num * 2 + 1); } return node; } // 根據數組生成二叉樹 var tree = new Tree([3,2,4,8,7,null,10,null,null,5,9]); console.log(tree);
function ListNode(x){ this.val = x; this.next = null; } function LinkedList(arr){ if(!arr || arr.length === 0){ return new ListNode(null); } var head = new ListNode(arr[0]); var len = arr.length; var curr = head; for(var i = 1; i < len; i++){ var temp = new ListNode(arr[i]); curr.next = temp; curr = curr.next; } return head; } var ll = new LinkedList([3,2,4,8,7,10,5,9]); console.log(ll);
(function(){ /* Todo: This Array contains the input lines in sequence. Each of the elements is like a line of input. */ var test_lines =['5','1 2 3 3 5','3','1 2 1','2 4 5','3 5 3']; // Do not change the name of this array if you don't like bugs. /**************************************************************** Todo: Add your code here including the callback function of event 'rl.on()' and global variables except the statements and definitions of 'readline' and 'rl'. *****************************************************************/ /* global variables here */ var lines = 1; /* callback function of 'rl.on()' */ function main(line) { // Do not change the name of this function if you don't like bugs. var str = line.trim(); console.log('lines',lines++,':',str); } /**************** End of Your Code *****************/ (function(){ var test_len = test_lines.length; var test_it = gen(test_lines); var test_val = test_it.next(); while(test_len){ main(test_val.value); test_val = test_it.next(); test_len--; } function* gen(test_lines){ var len = test_lines.length; var i = 0; while(len){ yield test_lines[i]; i++; } } }()) }());