Sword Finger offer Solution - JavaScript Edition

Keywords: Front-end Windows less Javascript Assembly Language

1. Finding in Two-Dimensional Array

In a two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, to determine whether the array contains the integer.

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;
}
2. Replace blanks

Implement a function that replaces a space in a string with "% 20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

function replaceSpace(str){
    return str.replace(/ /g, '%20');
}
3. Print the linked list from end to end

Enter a linked list and print the value of each node of the list from end to end.

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function printListFromTailToHead(head)
{
    // write code here
    if(!head){
		return 0;
	}else{
		var arr = new Array();
		// Note that it can't be written as head. val!= null
		while(head){
			arr.push(head.val)
			head = head.next;
		}
		return arr.reverse()
	}
}
  1. Enter the results of the pre-order and middle-order traversals of a binary tree, and rebuild the binary tree. It is assumed that the results of the input preamble traversal and the intermediate order traversal do not contain duplicate numbers. For example, the binary tree is reconstructed and returned if the pre-order traversal sequence {1,2,4,7,3,5,6,8} and the middle-order traversal sequence {4,7,2,1,5,3,8,6} are input.
/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function reConstructBinaryTree(pre, vin)
{
    // Judge the boundary first
	if(pre.length == 0 || vin.length == 0){
		return 0;
	}else{
		// Get the position in the ordinal traversal
		var index = vin.indexOf(pre[0]);
		// Get the right and left subtrees
		var left = vin.slice(0,index);
		var right = vin.slice(index+1,vin.length);
		var node = new TreeNode();
		node.val = vin[index];
		node.left = reConstructBinaryTree(pre.slice(1,index+1),left);
		node.right= reConstructBinaryTree(pre.slice(index+1,pre.length),right);
		return node;
		
	}
}
  1. Two stacks are used to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.
var stack1 = [];
var stack2 = [];
function push(node)
{	// Stack on the normal stack
	stack1.push(node)
}
// length judgment is not needed because it affects time complexity.
function pop()
{
	// Just put stack 1 in stack 2.
	var tem = stack1.pop()
	while(tem){
        stack2.push(tem)
		tem = stack1.pop()
    }
    var result =  stack2.pop()
	// But note that stack 1 is empty now, so that the next loop will report an error and import stack 2 back to stack 1
	tem = stack2.pop()
	while(tem){
		stack1.push(tem)
		tem = stack2.pop()
	}
	return result;
}
  1. Moving the initial elements of an array to the end of the array is called the rotation of the array. Input a rotation of an array with a non-recursive emission reduction order, and output the smallest element of the rotation array. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, and the minimum value of the array is 1. NOTE: All elements given are greater than 0. If the array size is 0, return 0.
function minNumberInRotateArray(rotateArray){
    var len = rotateArray.length;
    if(len === 0){
        return 0;
    }
    return Math.min.apply(null,rotateArray);
}
  1. We all know the Fibonacci sequence. Now we need to input an integer n. Please output the nth term of the Fibonacci sequence. N<=39
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;
}

8. A frog can jump up a step or two at a time. Find out how many jumping methods the frog can use to jump up an n-step.

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;
}

9. A frog can jump up a step or two at a time... It can also jump to level n. Find out how many jumping methods the frog can use to jump up an n-step.

function jumpFloorII(number){
return Math.pow(2, number - 1);
} 
  1. We can use 21 small rectangles to cover larger rectangles horizontally or vertically. How many ways are there to cover a 2*n rectangle with n 21 small rectangles without overlapping?
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;
}
  1. Input an integer and output the number of 1 in the binary representation of that number. Negative numbers are represented by complements.
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);
}
  1. Given a double type floating-point base and an int type integer exponent. Find exponential power of base.
function Power(base, exponent){
    return Math.pow(base, exponent);
}
  1. Input an integer array and implement a function to adjust the order of numbers in the array, so that all odd numbers are in the first half of the array, all even numbers are in the second half of the array, and ensure that the relative positions between odd and odd numbers, even and even numbers remain unchanged.
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);
}
  1. Input a list and output the reciprocal k node in the list.
/*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;
}
  1. Input a list, invert the list, output all elements of the list.
/*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;
}
  1. Input two monotonically increasing linked lists, output two combined linked lists, of course, we need to synthesize the linked list to meet the monotonic rule.
/*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;
    }
    //Preventing memory leaks
    curr = result.next;
    result.next = null;
    result = curr;
    curr = curr1 = curr2 = null;
    return result;
}
  1. Enter two binary trees A and B to determine whether B is a substructure of A. (ps: We agree that an empty tree is not a substructure of any tree)
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;
        }
    }
}
  1. Operate a given binary tree and transform it into a mirror image of the source binary tree.
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);
    }
}
  1. Input a matrix and print out each number in clockwise order from outside to inside. For example, if you input the following matrix: 1 23 4 5 6 7 9 9 11 12 13 14 15 16, then print out the numbers 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10.
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;
}
  1. Define the data structure of the stack. Implement a min function in this type that can get the minimum elements of the stack.
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);
}
  1. Enter two integer sequences. The first sequence represents the stack's entry order. Please determine whether the second sequence is the pop-up order of the stack. Assume that all the numbers pushed into the stack are unequal. For example, sequence 1, 2, 3, 4, 5 is the input sequence of a stack, sequence 4, 5, 3, 2, 1 is the corresponding pop-up sequence of the stack sequence, but 4, 3, 5, 1, 2 can not be the pop-up sequence of the stack sequence. (Note: The lengths of these two sequences are equal)
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;
}
  1. Each node of the binary tree is printed from top to bottom, and the same layer node is printed from left to right.
/* 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;
}
  1. Enter an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. If yes, output Yes, otherwise output No. Assume that any two numbers of the input array are different from each other. (The test case is false/true, not'Yes'/'No'in the title.)
/* 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));
    }
}
  1. Input a binary tree and an integer, print out all paths with the sum of the node values in the binary tree as the input integer. A path is defined as a path from the root node of a tree down to the node through which the leaf node passes.
/* 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;
    }
}
  1. Enter a complex linked list (each node has a node value and two pointers, one pointing to the next node, and the other pointing to any node), and return the result as the head of the replicated complex linked list. (Note that in the output, do not return the node reference in the parameter, otherwise the judgement program will return to null directly)
function Clone(pHead)
{
    if(!pHead){
        return null;
    }
    var head = new RandomListNode(pHead.label);
    head.random = pHead.random;
    head.next = Clone(pHead.next);
    return head;
}
  1. Enter a binary search tree and convert the binary search tree into a sorted bidirectional list. Requirements can not create any new nodes, can only adjust the pointer of the node in the tree.

The left subtree is constructed into a bidirectional list, which returns the end of the left subtree and connects it to the left of the root. The right subtree is constructed into a two-way list, appended to the root node, and returned to the endpoint. Left traversal returns the list to the first node, that is, the first node of the required bidirectional list.

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;
    }
}
  1. Enter a string and print out all the permutations of the characters in the string in dictionary order. For example, if you input the string a B c, you print out all the strings abc, a C b, bac, B C a, cab and cba that can be arranged by the characters a,b,c.
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){  //Duplicate removal
      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);   //To flash back
        }
    }
}
  1. There is a number in the array that appears more than half the length of the array. Find out that number. For example, enter an array of length 9 {1, 2, 3, 2, 2, 2, 5, 4, 2}. Since the number 2 appears five times in the array, more than half the length of the array, output 2. If not, output 0.
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;
}
  1. Enter n integers and find out the smallest number of K. For example, if you input 8 digits: 4, 5, 1, 6, 2, 7, 3, 8, the smallest 4 digits are 1, 2, 3, 4.
function GetLeastNumbers_Solution(input, k){
    if(!input || input.length < k){
        return [];
    }
    return input.sort(function(a,b){
        return a - b
    }).slice(0, k);
}
  1. Occasionally HZ will take some professional questions to fool those non-computer majors. Today, after the meeting of the test group, he spoke again: in the old one-dimensional pattern recognition, it is often necessary to calculate the maximum sum of continuous subvectors. When the vectors are all positive, the problem can be solved very well. However, if a vector contains negative numbers, should it contain a negative number and expect that the positive number next to it will make up for it? For example: {6,-3,-2,7,-15,1,2,2}, the maximum sum of continuous subvectors is 8 (starting from the 0th to the 3rd). Will you be fooled by him? (The length of the subvector is at least 1)
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;
}
  1. Find out the number of occurrences of 1 in integers 1-13, and the number of occurrences of 1 in integers 100-1300? For this reason, he counted the numbers 1, 10, 11, 12, 13 contained in 1 to 13, so there were six times, but he had no problem with the latter. ACMer wants you to help him and make the problem more general, so that you can quickly find the number of times 1 occurs in any nonnegative integer interval.
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;
}
  1. Input a positive integer array, splice all the numbers in the array into one number, print the smallest of all the numbers that can be spliced. For example, the input array {3, 32, 321} prints out the minimum number of the three numbers that can be arranged as 32123.
function PrintMinNumber(numbers)
{
    if(!numbers || numbers.length === 0){
        return [];
    }
    var result = [];
    var temp = '';
    ordering(numbers);
    result = result.map(Number).reduce(function(min , a){  //minimum value
      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);   //To flash back
        }
    }
}
  1. Ugly Number is a number that contains only factors 2, 3 and 5. For example, 6 and 8 are ugly numbers, but 14 is not because it contains factor 7. Traditionally, we regard 1 as the first ugly number. Find the N ugly number in the order from small to large.
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];
}
  1. Find the first character that appears only once in a string (1 <= string length <= 10000, all composed of letters) and return its position
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);
}
  1. Inverse Array Pairs

In an array, if the first number is larger than the last number, the two numbers form an inverse pair. Input an array to find the total number of inverse pairs in the array P. And the output of P to 1000000007 is given. That is to say, output P%1000000007

What does that mean?

It is to determine how many pairs of numbers are in an array, which is larger in front than in the back.

For example: [1, 2, 3, 4, 5, 6, 0], 1 and 0 are one pair, but 3 and 5 are not.

Due to the limitation of time and space complexity, js It seems that we can't finish this problem, so we use it. c++ Complete.

Actually, practical violence is not unavoidable either., But the cost is high.,High time complexity

Time complexity is O(n^2)

function InversePairs(data)
{
    let len = data.length;
    var res = 0;
    for(let i = 0; i<len;i++){
        for(let j = i;j<len;j++)
            if(data[i]>data[j])
                res ++;
    }
    return res;
}
console.log(InversePairs([1,2,3,4,5,6,7,0]))
// res = 7

Optimizing it to O(nlogn) is much better.

Merge sort can be used:

Reference resources: Explanation from Niuke.com

(a) Decomposition the array of length 4 into two subarrays of length 2;

(b) The two-length arrays are decomposed into two subarrays of Chengdu-1.

(c) Combining, sorting and counting the inverse pairs of subnumbers of length 1;

(d) Combining and sorting the subnumbers of length 2, and counting the reverse pairs;

In Figures (a) and (b), we first split the array into two sub-arrays of length 2, and then split the two sub-arrays into two sub-arrays of length 1, respectively. Next, we merge adjacent subarrays and count the number of reverse pairs. In the first pair of subarrays {7} and {5} of length 1, 7 is greater than 5, so (7,5) constitutes an inverse pair. There are also reverse pairs (6,4) in the second pair of subarrays {6} and {4} of length 1. Since we have counted the inverse pairs within these two pairs of subarrays, we need to sort these two pairs of subarrays as shown in figure (c) above, so as not to repeat the statistics in the future statistical process.

Next, we count the inverse pairs between two subarrays of length 2. The process of merging subarrays and counting inverse pairs is shown in the following figure.

We first point to the end of two subarrays with two pointers, and compare the numbers pointed by two pointers at a time. If the number in the first subarray is larger than that in the second, an inverse pair is formed, and the number of inverse pairs equals the number of remaining numbers in the second subarray, as shown in Figures (a) and (c). If the number of the first array is less than or equal to the number of the second array, it does not constitute an inverse pair, as shown in Figure b. For each comparison, we copy large numbers from the back to a secondary array to ensure that the numbers in the auxiliary array (recorded as copy) are sorted incrementally. After copying large numbers to auxiliary arrays, move the corresponding pointer forward one bit, and then make the next round of comparison.

Procedure: First, the array is divided into subarrays. First, the number of inverse pairs in the subarray is counted, and then the number of inverse pairs between two adjacent subarrays is counted. In the process of statistical inverse pairing, it is necessary to sort arrays. If we are familiar with sorting algorithms, it is not difficult to find that this process is actually merge sorting.

class Solution {
public:
    long long InversePairsCore(vector &data, vector&copy, 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 data) {
        int length = data.size();
        if(length <= 0)
            return 0;
        vector 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;
    }
};

JavaScript Versions

function InversePairs(data)
{
    if(!data||data.length<2) return 0;
 
    var copy = data.slice(),
        count = 0;
    count = mergeSort(data,copy,0,data.length-1);
    return count%1000000007;
}
 
function mergeSort(data,copy,start,end){
    if(end===start) return 0;
    var mid = (end-start)>>1,
        left = mergeSort(copy,data,start,start+mid),
        right = mergeSort(copy,data,start+mid+1,end),
        count = 0,
        p = start+mid,//The last subscript of the previous array
        q = end,//Subscription of the latter array
        copyIndex = end;//Auxiliary array subscripts, counting from the last
 
    while(p>=start&&q>=start+mid+1){
        if(data[p]>data[q]){
            count+=q-start-mid;
            copy[copyIndex--] = data[p--];
        }else{
            copy[copyIndex--] = data[q--];
        }
    }
 
    while(p>=start){
        copy[copyIndex--] = data[p--];
    }
 
    while(q>=start+mid+1){
        copy[copyIndex--] = data[q--];
    }
    return left+right+count;
}
  1. Enter two linked lists to find their first common node.
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;
    }
}
  1. Statistics the number of times a number appears in a sorted array.
function GetNumberOfK(data, k){
    return data.reduce(function(count, a){
        return a === k ? count+1 :count;
    }, 0);
}
  1. Input a binary tree to find the depth of the tree. From root node to leaf node, a path is formed by successive nodes (including root and leaf nodes), and the longest path is the depth of the tree.
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--;
    }
}
  1. Input a binary tree to determine whether the binary tree is a balanced binary tree.
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--;
        }
    }
}
  1. Except for two numbers in an integer array, the other numbers appear twice. Write a program to find the two numbers that appear only once.

    Method 1

function FindNumsAppearOnce(array){
    if (!array || array.length < 2)
        return [];
    return array.sort().join(',').replace(/(\d+),\1/g,"").replace(/,+/g,',').replace(/^,|,$/, '').split(',').map(Number);
}

Method 2

function FindNumsAppearOnce(array)
{
    // write code here
    // return list, such as [a,b], where ab is two numbers that appear once
    var arr = [];
    for(var i = 0; i < array.length; i++) {
        if(array.indexOf(array[i]) === array.lastIndexOf(array[i])) {
            arr.push(array[i]);
        }
    }
    return arr;
}
  1. Xiao Ming likes mathematics very much. One day when he was doing his math homework, he asked to calculate the sum of 9 to 16. He immediately wrote the correct answer is 100. But he wasn't satisfied with that. He was wondering how many consecutive positive sequence sums up to 100 (at least two numbers). Before long, he got another set of sequences with a continuous positive sum of 100: 18, 19, 20, 21, 22. Now let's leave the problem to you. Can you find out all the continuous positive sequences for S very quickly?
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);
    }
}
  1. Input an incremental sorted array and a number S. Find two numbers in the array. Their sum is exactly S. If the sum of many pairs of numbers equals S, the product of the output two numbers is the smallest.
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];
}
  1. There is a shift instruction in assembly language called loop left shift (ROL). Now there is a simple task, which is to simulate the operation result of this instruction with strings. For a given character sequence S, you can output the sequence after shifting its loop left to K bit. For example, the character sequence S= "abcXYZdef" requires the output of the loop to move three bits left, that is, "XYZdefabc". Is it simple? OK, get it done!
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;
}
  1. A new employee, Fish, has recently arrived. Every morning, he always carries an English magazine and writes some sentences in his notebook. Colleague Cat was interested in what Fish had written. One day he borrowed it from Fish and couldn't read it. For example, "student. a am I". Later, I realized that this guy had reversed the order of sentences and words. The correct sentence should be "I am a student." Cat is not good at flipping these words one by one. Can you help him?
function ReverseSentence(str){
    return str.split(' ').reverse().join(' ');
}
  1. LL is in a very good mood today, because he went to buy a deck of playing cards, and found that there were actually two kings and two Xiaowangs in it. (One deck was originally 54 ^ ^ ^). He randomly drew five cards out of it, trying to test his luck and see if he could draw Shunzi. If he did, he decided to buy sports lottery tickets. Hey!! "Red Heart A, Spades 3, Xiaowang, Wang, Fang Dian 5, Oh My God!" Not Shunzi... LL was unhappy. He thought about it and decided that Da Xiaowang could be regarded as any number, and A as 1,J as 11,Q as 12,K as 13. The five cards above can be changed into "1, 2, 3, 4, 5" (the king and the king are considered as 2 and 4 respectively), "So Lucky!". LL decided to buy a sports lottery. Now, ask you to use this card to simulate the above process, and then tell us how lucky LL is. For convenience, you can think of Wang Xiaowang as 0.
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;
}
  1. Every year on June 1 children's day, the oxen will prepare some small gifts to visit the orphanage children, and this year is also true. HF, as a veteran veteran of Niuke, naturally also prepared some games. Among them, there is a game like this: First, let the children form a big circle. Then, he randomly assigned a number m, so that the children numbered 0 began to count. Every time the kid who shouts M-1 sings a song, he can choose any gift in the gift box, and no longer go back to the circle. Starting from his next child, he continues to count 0 m-1. This goes on.... Until the last kid, he can not perform and get the famous detective Conan. ” Collection edition (limited quota!! ^ ^ ^ ^ ^). Please try to think, which child will get this gift? (Note: Children's numbers range from 0 to n-1)

    Joseph Ring Problem

    Formula deduction can be seen as follows: https://www.zhihu.com/question/20065611/answer/605352217

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;
}
  1. To find 1+2+3+...+n, we must not use the keywords of multiplication and division, for, while, if, else, switch, case and other conditional judgment statements (A?B:C).
function Sum_Solution(n){
  var sum = 0;
  plus(n);
  return sum;
 
  function plus(num){
    sum += num;
    num > 0 && plus(--num);
  }
}
  1. Write a function to find the sum of two integers, requiring that +, -, *, / four operation symbols should not be used in the function body.
function Add(num1, num2){
    var sum, carry;
    do{
        sum = num1 ^ num2;
        carry = (num1 & num2) << 1;
        num1 = sum;
        num2 = carry;
    }while(num2 != 0);
    return num1;
}
  1. Converting a string to an integer requires that library functions that do not use strings to convert integers should not be used. If the value is 0 or the string is not a valid value, it returns 0.
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;
}
  1. All numbers in an array of length n are in the range of 0 to n-1. Some numbers in an array are duplicated, but it is not known how many are duplicated. I don't know how many times each number is repeated. Find any duplicate number in the array. For example, if an array {2,3,1,0,2,5,3} with an input length of 7 is input, the corresponding output is the first duplicate number 2.
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;
}
  1. Given an array A[0,1,...,n-1], construct an array B[0,1,...,n-1], where the element B [i] = A [0] A [1] * A [i-1] A [i+1] * A [n-1]. Division cannot be used.
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;
}
  1. Implement a function to match regular expressions including'.'and'. The character'. 'in the pattern represents any character, and'' indicates that the character before it can appear any number of times (including 0 times). In this topic, matching means that all characters of a string match the entire pattern. For example, the string "a a a" matches the pattern "a.a" and "abaca", but neither "aa.a" nor "ab*a"
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);
}

c + + Judgment Solution

class Solution {
public:
    bool match(char* str, char* pattern)
    {
        if (pattern[0] == 0 && str[0] == 0)
        {
            return true;
        }
   
        if (pattern[0] != 0 && pattern[1] == '*')
        {
            if (match(str, pattern + 2))
                return true;
        }
   
        if ((pattern[0] == '.' && str[0]) || str[0] == pattern[0])
        {
            if (match(str + 1, pattern + 1))
                return true;
            if (pattern[1] == '*' && match(str + 1, pattern))
            {
                return true;
            }
        }
   
        return false;   
    }
};
  1. Implement a function to determine whether a string represents a value (including integers and decimals). For example, strings "+100","5e2","-123","3.1416" and "-1E-16" all represent values. But "12e", "1a3.14", "1.2.3", "+5" and "12e+4.3" are not.
function isNumeric(s){
    var reg = /^[+-]?(?:(\d+)(\.\d+)?|(\.\d+))([eE][+-]?\d+)?$/;
    return reg.test(s);
}
  1. Implement a function to find the first character in the character stream that appears only once. For example, when only the first two characters "go" are read out from the character stream, the first character that appears only once is "g". When the first six characters "google" are read from the stream, the first character that appears only once is "l".

    If there is no character that appears once in the current character stream, return the # character.
    
function Init(){
    streamNums = [];   //Define a global variable without var
    streamNumsLen = 256;   //Define a global variable without var
    streamNumsIndex = 0;   //Define a global variable without 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;
}
  1. A list contains rings. Please find the entry node of the ring of the list. Otherwise output null
/*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;
    }
}
  1. In a sorted list, there are duplicate nodes. Please delete the duplicate nodes in the list. The duplicate nodes are not reserved and return to the header pointer of the list. For example, the chain table 1 - > 2 - > 3 - > 3 - > 4 - > 4 - > 5 is treated with 1 - > 2 - > 5.
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;
        }
    }
}
  1. Given a binary tree and one of its nodes, find the next node in the middle traversal order and return. Note that the nodes in the tree contain not only left and right child nodes, but also pointers to the parent node.
    1. If the binary tree is empty, it returns empty.
    2. If the right child of the node exists, a pointer is set to start from the right child of the node, and the leaf node found along the pointer pointing to the left child node is the next node.
    3. Nodes are not root nodes. If the node is the left child of its parent node, it returns to the parent node; otherwise, it continues to traverse the parent node of its parent node upwards, repeating the previous judgment and returning the result.
/*function TreeLinkNode(x){
    this.val = x;
    this.left = null;
    this.right = null;
    this.next = null;
}*/
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;
    }
}
  1. Please implement a function to determine whether a binary tree is symmetrical. Note that if a binary tree has the same mirror image as the binary tree, it is defined as symmetric.
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);
    }
}
  1. Please implement a function to print the binary tree in zigzag, that is, the first line is printed in left-to-right order, the second layer is printed in right-to-left order, the third line is printed in left-to-right order, and so on.
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;
}
  1. Print the binary tree layer by layer from top to bottom, and output the same layer node from left to right. Each layer outputs one line.
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;
}
  1. Please implement two functions to serialize and deserialize the binary tree, respectively
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;
    }
}
  1. Given a binary search tree, find the largest k node. For example, in 5/37/\27/\2468, the value of the third node is 4 in the order of node value size.
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;
    }
}
  1. How to get the median in a data stream? If an odd number of values are read from the data stream, the median is the value in the middle after all the values are sorted. If an even number of values are read from the data stream, then the median is the average of the middle two numbers after all the values are sorted.
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]
    }
}
  1. Given an array and the size of the sliding window, find the maximum values in all sliding windows. For example, if the input array {2,3,4,4,2,2,6,6,2,2,2,2,2,2,2,2,2,2,2,2,2,2,6,6,6,6,6,6,6,6,5} and the size of sliding window 3, there are six sliding windows for array {2,3,3,4,4,2,2,2,2,6,6,6,2,2,2,2,2,2,6,2,2,2,2,5,5,1}, {2,{2,[3,4,4,2,4,2,2,4,2,2,5,5,1},{{2,2,3,3,3,3,3,{,{,2}, {2, 3, 4, [2, 6, 2], 5 1}, {2,3,4,2, [6,2,5], 1}, {2,3,4,2,6, [2,5,1]}.
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;
}
  1. Design a function to determine whether there is a path containing all the characters of a string in a matrix. The path can start from any lattice in the matrix, and each step can move one lattice to the left, right, up and down in the matrix. If a path passes through a lattice in the matrix, the path can no longer enter the lattice. For example, a b c e s f c s a d e matrix contains a path of the string "bcced", but the matrix does not contain an "abcb" path, because the first character B of the string occupies the first row and the second lattice in the matrix, and the path cannot enter the lattice again.
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 = 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;
    }
}
  1. There is a square of m rows and n columns on the ground. A robot moves from a grid of coordinates 0,0. Each time, it can only move one grid in four directions: left, right, up and down, but it can't enter a grid whose digit sum of row coordinates and column coordinates is larger than k. For example, when k is 18, the robot can enter the grid (35,37), because 3+5+3+7 = 18. However, it cannot enter the grid (35,38), because 3+5+3+8 = 19. How many grids can the robot reach?
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 = 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;
    }
}

Manual testing framework

  • Binary Tree Construction
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;
}
// Generate binary trees from arrays, sequence
var tree = new Tree([3,2,4,8,7,null,10,null,null,5,9]);
console.log(tree);
  • One-way list construction
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);
  • Node.js multi-line input test for Niukeen (update browser to support es6 grammar if you can't run)
(function(){
    var test_lines =['5','1 2 3 3 5','3','1 2 1','2 4 5','3 5 3'];
    var lines = 1;
    function main(line) {
        var str = line.trim();
        console.log('lines',lines++,':',str);
    }
    (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++;
            }
        }
    }())
}());

Posted by REDFOXES06 on Tue, 30 Jul 2019 21:17:58 -0700