preamble
Recently practiced some front-end algorithm questions, now do a summary, the following topics are personal writing, not the standard answer, if there is an error welcome to point out that there is a new idea of a question of friends can also be published in the comments section ideas, learn from each other 🤭
title
Topic 1: Finding in a 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. Complete a function that takes such a two-dimensional array and an integer and determines whether the array contains the integer.
function sortList(array, num) {
// Solution 1.circulateindexOfconsult (a document etc) With return subscript,If not, return-1
// for (let i = 0; i < ; i++) {
// if (array[i].indexOf(num) != -1) {
// return ('there are');
// }
// }
// Solution 2.嵌套circulate
// for(let i=0;i<;i++){
// for(let j=0;j<array[i].length;j++){
// if(array[i][j]==num){
// return 'there are'
// }
// }
// }
// Solution 3.Array flattening,after thatindexOffind
let newArray = toStr(array)
(newArray)
if ((num) != -1) {
return ('there are');
}
return ('没there are');
}
// Array flattening
function toStr(arr) {
return ().split(',').map(item => {
return Number(item)
})
}
let ary = [[1, 2, 3, 4], [2, 3, 4, 5]]
sortList(ary, 5)
Topic 2: Replace Spaces: Implement a function that replaces spaces in a string with "%20". For example, if the string is We Are Happy, then the replaced string will be We%20Are%20Happy.
function replaceSpace(str) {
// Solution 1: Violent for-loop comparison
// let newStr=''
// for(let i=0;i<;i++){
// if(str[i]==''){
// newStr+='%20'
// }else{
// newStr+=str[i]
// }
// }
// (newStr)
// return newStr
// Solution 2: split into an array, then join to string
// let newStr = split to array, then join to string (" ").join("%20"); // (newStr); // (newStr) = split to array, then join to string (" ").
// (newStr)
// return newStr
// Solution 3: Regular
// var reg = / /g;
// let newStr=(reg, "%20"); // (newStr)
// (newStr)
// return newStr
}
replaceSpace('We Are Happy')
Topic 3: Printing a chained table from end to end: Input a chained table and print the value of each node of the chained table from end to end.
Idea, using the characteristics of the stack first-in, first-out, simulate the pressure stack, and then out of the stack to achieve the
class Node {
constructor(data) {
= data
= null
}
}
function printNode(node) {
(node)
// stack implementation
let stock = new Array()
let NodeNextElm = node
while (NodeNextElm !== null) {
// (stock)
()
NodeNextElm =
}
while ( > 0) {
(())
}
}
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
= node2
= node3
printNode(node1)
Topic 4: Reconstructing a Binary Tree: Input the result of a leading and middle order traversal of a binary tree. Assume that neither the preceding nor the middle order traversal result contains duplicate numbers. For example, if you enter the sequence {1,2,4,7,3,5,6,8} for the preceding traversal and {4,7,2,1,5,3,8,6} for the middle traversal, rebuild the binary tree and return it.
Idea: Pre-order traversal (root left and right) and mid-order traversal (left root right)
I. [1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6] -> val=>1 ->L([2,4,7],[4,7,2]) & R([3,5,6,8],[5,3,8,6]) Root node 1 ,with left and right nodes
II. L([2,4,7],[4,7,2]) -> val=>2 ->L([4,7],[4,7]) & & & R(null , null) Root node 2 (left node of genus 1) ,with left node, no right node
R([3,5,6,8],[5,3,8,6]) -> val=>3 ->L([5],[5]) & & & R([6,8],[6,8]) Root node 3 (right node of genus 1) ,with left and right nodes
iii. L([4,7],[4,7]) ->val=>4 -> L(null , null) && R([7],[7]) Root node 4 (left node of genus 2) ,with right node, without left node
R([6,8],[8,6]) -> val=>6 -> L([8] , [8]) && R(null , null) Root node 6 (right node of genus 3), with left node, no right node
L([5],[5]) -> val=>5->(null,null)-> termination End node 5 (left node of genus 3)
IV. R([7],[7]) -> val=>7 -> termination End node 7 (right node of genus 4)
L([8],[8]) -> val=>8 -> termination End node 8 (left node of genus 6)
function rebuildBinaryTree(front, center) {
if (!front || == 0) {
if (!front || == 0) { return null; }
}
var TreeNode = {
val: front[0]
}; var TreeNode = { val: front[0]; }
for (var i = 0; i < ; i++) {
//find the middle order traversal root node position
if (center[i] === front[0]) {
//For a medium order traversal, the nodes to the left of the root node are on the left side of the binary tree, and the nodes to the right of the root node are on the right side of the binary tree
= rebuildBinaryTree((1, i + 1), (0, i));
= rebuildBinaryTree((i + 1), (i + 1));
}
}
return TreeNode.
}
let tree = rebuildBinaryTree([1, 2, 4, 7, 3, 5, 6, 8], [4, 7, 2, 1, 5, 3, 8, 6])
(tree)
Topic 5: Implementing a Queue with Two Stacks: Implement a queue with two stacks, complete with the Push and Pop operations of the queue.
Idea: use two arrays to simulate a stack, one for push and one for pop
let stack_push = []
let stack_pop = []
function pushData(data) {
stack_push.push(data)
}
function popData() {
if (stack_pop.length > 0) {
(stack_pop.pop())
} else {
if (stack_push.length > 0) {
while (stack_push.length > 0) {
stack_pop.push(stack_push.pop())
}
(stack_pop.pop());
} else {
('The queue is empty.');
}
}
}
pushData(1)
pushData(2)
pushData(3)
pushData(4)
(stack_push);
(stack_pop);
popData()
(stack_push);
(stack_pop);
pushData(5)
(stack_push);
(stack_pop);
popData()
popData()
popData()
popData()
popData()
(stack_push);
(stack_pop);
Topic 6: Rotating the smallest number of an array: Moving a number of elements from the very beginning of an array to the end of the array is what we call a rotation of the array. Input a rotation of a non-decreasing sorted array and output the smallest element of the rotated array. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, which has a minimum value of 1. NOTE: All elements given are greater than 0. If the array size is 0, return 0.
function revoleArray(array) {
let min = array[0];
let index = 0;
for (let i = 0; i < ; i++) {
if (array[i] < min) {
min = array[i]
index = i
}
}
let newArray = (0, index)
let newArray2 = (index)
return (newArray)
}
let newArray = revoleArray([3, 4, 5, 1, 2])
(newArray)
Topic 7: Fibonacci series: We all know the Fibonacci series, now ask for an integer n, please output the nth term of the Fibonacci series, n<= 39.
Idea: Fibonacci series:[1,1,2,3,5,8,13,...] Each number is equal to the sum of the previous two numbers
//Solution 1:recursive (calculation)
function fbnq(n) {
if (n <= 1) {
return 1
}
return fbnq(n - 1) + fbnq(n - 2)
}
// Solution 2:circulate
function Fibonacci(n) {
if (n <= 1) {
return 1;
} else {
let before_one=0,before_two=0,result=0,List=[]
for(let i=0;i<=n;i++){
before_one=List[i-1]>=0?List[i-1]:0
before_two=List[i-2]>=0?List[i-2]:0
result=before_one + before_two
if(result<=1)result=1
(result)
}
return List[n]
}
}
let a = fbnq(5)
(a);
let b = Fibonacci(5)
(b);
Topic 8: Step-hopping: A frog can jump up 1 step or 2 steps at a time. Find the total number of ways the frog can jump up a step of n steps.
Idea: jump(1)=1 jump(2)=2 jump(3)=3 jump(4)=5 jump(5)=8 Similar to the Fibonacci series except that the first two terms become 1, 2
function jump(n){
if(n<=2){
return n;
}
return jump(n-1) + jump(n-2)
}
let jumpNum=jump(5)
(jumpNum);
Topic 9: Perverted Step Jumping: A frog can jump up 1 step at a time or 2 steps at a time ...... It can also jump up n steps. Find the total number of ways the frog can jump up an n-step ladder.
Idea: jump(1)=1 jump(2)=2 jump(3)=4 jump(4)=8 nth power of 2
function btJump(n){
// Solution 1: Use the bitwise operator 2 to the nth power is easiest to use the bitwise operator 1<<n (shift 1 to the left by n digits) 1:0001 2:0010 4:0100 8:1000
// return 1<<(--n).
// Solution 2: Recursion
if(n<=1){
return n
}else{
return 2*btJump(n-1)
}
}
let jumpNum=btJump(5)
(jumpNum).
Topic X: Rectangular covering: we can use 2A small rectangle of 1 is placed horizontally or vertically to cover a larger rectangle. What would be the best way to cover the larger rectangle with n 2How many ways are there to cover a large 2*n rectangle with a small rectangle of 1 without overlap?
function rectCover(number) {
if (number <= 2) {
return number;
} else {
return rectCover(number - 1) + rectCover(number - 2);
}
}
let rectNum=rectCover(4)
(rectNum);
Topic XI: Number of 1's in Binary: Input an integer and output the number of 1's in the binary representation of the number. Negative numbers are represented as complements.
Ideas: First, the use of split ('') will be converted to an array of characters and then reduce to accumulate Second, violent for loop judgment
function countOneNum(num) {
let count=0; // toString(2) to binary.
// toString(2) converted to binary.
// Solution 1: Use split('') to convert to an array of characters and then reduce to add them up
count = (2).split('').reduce((acc, cur) => {
(acc, cur)
return acc + parseInt(cur)
}, 0);
let Binary=(2)
// Solution 2: for loop
for(let i=0;i<;i++){
if(Binary[i]==1)count++
}
return count
}
let count = countOneNum(5)
(count).
Topic XII: Integer Subdivision of Values: Given a floating point number base of type double and an integer exponent of type int, find the exponent subdivision of base.
function md(base,exponent){
if(exponent<0){
if(base<0){
return 'I don't know how to make it negative.'
}else{
return 1/md(base,-exponent)
}
}else if(exponent==0){
return 1
}else{
return base*md(base,exponent-1)
}
}
let total=md(2.33,-5)
(total);
Topic 13: Reordering an array so that the odd numbers are in front of the even numbers: Input an array of integers, implement a function to reorder the numbers in the array so that all the odd numbers are in the first half of the array, and all the even numbers are in the second half of the array, and make sure that the relative positions of the odd numbers and the odd numbers, and of the even numbers and the even numbers, are unchanged.
Idea: loop through the parity list, then concat and merge
function changeArray(array) {
let jList = [], oList = []
(item => {
if (item % 2 == 0) {
(item)
} else {
(item)
}
});
return (oList)
}
let NewArray = changeArray([2, 3, 4, 5, 9, 8, 7])
(NewArray);
Topic 14: The penultimate kth node in a chained table: Input a chained table and output the penultimate kth node in that chained table.
Idea: simulate the stack will push the chain table into the stack, and then determine whether k is greater than or equal to the length of the chain table, the inverse array and then take out the node with the subscript k-1
class Node{
constructor(data){
=data
=null
}
}
function getIndexNode(node,index){
let stack=[]
let nextNodeElm=node
while(nextNodeElm!=null){
()
nextNodeElm=
}
if(<index){
return 'Input nodes should be less than or equal to the length of the link table.'
}
()
return stack[index-1]
}
const node1=new Node(1)
const node2=new Node(2)
const node3=new Node(3)
const node4=new Node(4)
const node5=new Node(5)
=node2
=node3
=node4
=node5
let node=getIndexNode(node1,5)
(node)
Topic 15: Reverse Chained Table: Input a chained table, reverse the table and output all the elements of the chained table.
class Node {
constructor(data) {
= data
= null
}
}
function revolveNode(node) {
if (node == null) {
return false;
}
let p1 = node, p2 = null, temp = null;
while (p1) {
temp = ;
= p2;
p2 = p1;
p1 = temp;
}
return p2;
}
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
const node4 = new Node(4)
const node5 = new Node(5)
= node2
= node3
= node4
= node5
let node = revolveNode(node1)
(node)
Topic 16: Merge two sorted linked lists: input two monotonically increasing linked lists, output two linked lists synthesized linked lists, of course, we need to synthesize the linked lists to satisfy the monotonicity of the non-decreasing rule.
class Node {
constructor(data) {
= data
= null
}
}
function Merge(node1, node2) {
(node1, node2);
if (node1 == null) {
return node2;
} else if (node2 == null) {
return node1;
}
var result = {};
if ( < ) {
result = node1;
= Merge(, node2);
} else {
result = node2;
= Merge(node1, );
}
return result;
}
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
const node4 = new Node(4)
const node5 = new Node(5)
const node6 = new Node(6)
const node7 = new Node(7)
const node8 = new Node(8)
const node9 = new Node(9)
const node10 = new Node(10)
= node2
= node3
= node5
= node6
= node7
= node8
= node9
= node10
let newNode=Merge(node1,node4)
(newNode);
Topic 17: Clockwise Printing of Matrices: Input a matrix and print each number in clockwise order from the outside to the inside.
For example, if the following matrix is entered:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The numbers 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10 are printed in order.
Idea: print out the first row in sequential order, then rotate the matrix counterclockwise and continue to print the first row until you're done
function rotateMatrix90Clockwise(matrix) {
const numRows = ;
const numCols = matrix[0].length;
let rotatedMatrix = new Array(numCols).fill(0).map(() => new Array(numRows));
for (let i = 0; i < numRows; i++) {
for (let j = 0; j < numCols; j++) {
rotatedMatrix[numCols - j - 1][i] = matrix[i][j];
}
}
return rotatedMatrix;
}
function printNum(array){
let list=(0,1)[0]
// (list);
let newList=()
while(>0){
(())
}
// (newList);
array=(1,)
if(==0){
return
}
let newArray=rotateMatrix90Clockwise(array)
printNum(newArray)
}
const originalMatrix = [
[1, 2, 3,4],
[5, 6,7,8],
[9,10,11,12],
[13,14,15,16]
];
printNum(originalMatrix);
Topic 18: Define a stack, implement the min function: Define the data structure of the stack, please implement a min function in the type that can get the smallest element of the stack.
let stack_push = []
let stack_pop = []
function pushData(data) {
stack_push.push(data)
}
function popData() {
if (stack_pop.length > 0) {
(stack_pop.pop());
} else {
if (stack_push.length > 0) {
while (stack_push.length > 0) {
stack_pop.push(stack_push.pop())
}
(stack_pop.pop());
} else {
('warehouse')
}
}
}
function searchMin() {
while (stack_pop.length > 0) {
stack_push.push(stack_pop())
}
let min = stack_push[0]
for (let index = 0; index < stack_push.length; index++) {
if (stack_push[index] < min) {
min = stack_push[index]
}
}
return min
}
pushData(1)
pushData(2)
pushData(3)
pushData(0)
pushData(4)
let min = searchMin()
(min);
Topic 19: Press-in-pop-out of a stack: Input two sequences of integers, the first sequence represents the order of press-in of a stack, please determine whether the second sequence is the order of pop-out of this stack. Assume that all the numbers pressed into the stack are not equal.
For example: Sequence 1,2,3,4,5 is the press-in sequence of a stack, and sequence 4,5,3,2,1 is a pop-out sequence corresponding to that press-in sequence, but 4,3,5,1,2 cannot be a pop-out sequence of that press-in sequence. (Note that the lengths of the two sequences are equal)
Ideas: i. Simulate a press-stack pop stack ii. Directly invert the array for pop comparisons
let stack_push = []
let stack_pop = []
function pushData(data) {
stack_push.push(data)
}
function popData() {
if (stack_pop.length > 0) {
(stack_pop.pop());
} else {
if (stack_push.length > 0) {
while (stack_push.length > 0) {
stack_pop.push(stack_push.pop())
}
(stack_pop.pop());
} else {
('warehouse')
}
}
}
function testStack(pushStack,popStack){
// Solution 1:Analog Stack Bouncing
// if( != ){
// return 'fault'
// }
// let NewPushStack=()
// let NewPopStack=()
// while(>0){
// pushData(())
// }
// while(stack_push.length>0){
// if(stack_push.pop() != ())return 'queer'
// }
// return 'properly'
// Solution 2:Directly invert the array forpopcomparisons
if( != ){
return 'fault'
}
let NewPopStack=()
while(>0){
if(() != ())return 'queer'
}
return 'properly'
}
let result=testStack([1,2,3,4,5],[5,4,3,2,1])
(result);
Topic XX: Copying a Complex Chained Table: Input a complex chained table (each node has a node value, as well as two pointers, one pointing to the next node, and the other special pointer pointing to any one of the nodes), and return the result as the head of the copied complex chained table. (Note that in the output, please don't return the node references in the parameters, otherwise the program will return null.)
function copyNode(pHead){
(pHead)
if (!pHead) {
return null;
}
// Copy head node
var node = new Node();
= ;
// Recursive other nodes
= copyNode();
return node;
}
class Node {
constructor(data) {
= data
= null
= null
}
}
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
= node2
= node3
= node2
= node3
= node1
let newNode=copyNode(node1)
(newNode);
Topic XXI: Arrangement of strings: Enter a string and print out all the arrangements of the characters in that string in dictionary order. For example, if you enter the string abc, print out all the strings abc, acb, bac, bca, cab, and cba that can be arranged by the characters a,b,c. Input description: Enter a string up to 9 in length (with possible duplication of characters), with characters consisting of upper and lower case letters only.
function permute(str, left = 0, right = - 1) { //abc left 2
(left,right)
// If the left border equals the right border, that means there is only one character left, print it
if (left === right) {
("Result: ", str); } else {
} else {
// iterate through each position from l to r
for (let i = left; i <= right; i++) {
// Swap the character at the current position i with the character at the left boundary l
str = swap(str, left, i);
("str:",str, "left:",left, "I:",i);
// recursively permute the remaining substrings (note that left+1 means excluding fixed characters)
permute(str, left + 1, right); // recursively permute the remaining substrings (note that left + 1 means exclude fixed characters).
// After returning from the recursion, the characters need to be swapped back to their original positions so that the next loop can use the original string
str = swap(str, left, i); // if you want to use the original string in a recursive loop, swap the characters back to their original positions.
}
}
}
function swap(str, i, j) {
// Convert the string to an array of characters
let arr = (''); // Deconstruct the swap element.
// Deconstruct the swap elements
[arr[i], arr[j]] = [arr[j], arr[i]]; // convert the modified array back into an array of strings.
// Convert the modified array back to a string
return ('');
}
permute('abc');
Topic XXII: Numbers Occurring More Than Half the Time in an Array: There is a number in an array that occurs more than half the time of the length of the array. Find this number. For example, enter an array of length 9 {1,2,3,2,2,2,2,5,4,2}. Since the number 2 appears 5 times in the array, which is more than half the length of the array, output 2. If it does not exist, output 0.
function moreAHalfNum(array){
let length=
let maxLength=(length/2)
let computedTotal={}
let maxNum=null
(item => {
if(computedTotal[item]){
computedTotal[item]++
if(computedTotal[item]>maxLength)maxNum=item
}else{
computedTotal[item]=1
}
});
return maxNum?maxNum:0
}
let num=moreAHalfNum([1,2,3,4,6,6,6,6,6])
(num);
Topic XXIII: Smallest K numbers: Enter n integers and find the smallest K numbers. For example, if you enter 8 numbers 4,5,1,6,2,7,3,8, the 4 smallest numbers are 1,2,3,4.
Idea: first sort sort, at this time the array is sorted from small to large, take the first k can be
function searchMinCountNum(array,K){
let NewArray=()
return (0,K)
}
let countNum=searchMinCountNum([2,1,8,9,6,5],3)
(countNum);
Topic XXIV: Arranging arrays into the smallest number: Enter an array of positive integers, splice all the numbers in the array to form a number, and print the smallest of all the numbers that can be spliced together. For example, if you enter the array {3, 32, 321}, then print the smallest number that can be arranged into these three numbers as 321323.
function PrintMinNumber(numbers) {
(function (a, b) {
var s1 = a + '' + b;
var s2 = b + '' + a;
for (var i = 0; i < ; i++) {
if ((i) > (i)) {
return 1
} else if ((i) < (i)) {
return -1;
}
}
return 1
})
(numbers);
var result = "";
(function (num) {
result = (num)
})
return result;
}
let num=PrintMinNumber([32,3,321])
(num);
Topic XXV: Ugly numbers (to be understood in depth): Numbers that contain only prime factors 2, 3 and 5 are called ugly numbers. For example, 6 and 8 are ugly numbers, but 14 is not, because it contains a factor of 7. It is customary to think of 1 as the first ugly number. Find the Nth ugly number in descending order.
function getUglyNumberSolution(index) {
if (index == 0) return 0
var uglys = [1];
var factor2 = 0, factor3 = 0, factor5 = 0;
for (var i = 1; i < index; i++) {
uglys[i] = (uglys[factor2] * 2, uglys[factor3] * 3, uglys[factor5] * 5)
if (uglys[i] == uglys[factor2] * 2) factor2++;
if (uglys[i] == uglys[factor3] * 3) factor3++;
if (uglys[i] == uglys[factor5] * 5) factor5++;
}
(uglys);
return uglys[index - 1]
}
let count=getUglyNumberSolution(11)
(count);
Topic XXVI: First character that occurs only once: Find the first character that occurs only once in a string (1<=string length<=10000, all composed of uppercase letters) and return its position.
function getFirstChar(str){
str=()
let chat={}
for (let i = 0; i < ; i++) {
if(chat[str[i]]){
chat[str[i]]++
}else{
chat[str[i]]=1
}
}
(chat);
for (let i = 0; i <= ; i++) {
if(chat[str[i]]==1){
return (str[i]) +"=>"+str[i]
}
}
return 'No characters that appear only once'
}
let index=getFirstChar('hheello')
(index);
Topic XXVII: Inverse pairs in arrays: two numbers in an array form an inverse pair if the preceding number is greater than the following number. Input an array and find the total number P of inverse pairs in this array.
function getReverseNum(array){
let count=0
let towNum=[]
if(>1){
towNum=(0,2)
(towNum);
if(towNum[0]>towNum[1]){
count++
}
return count + getReverseNum((2,))
}
return count
}
let num=getReverseNum([2,1,3,4,5,4,5,4,5,4,5,4])
(num);
Topic XXVIII: Number of times a number appears in a sorted array: Count the number of times a number: appears in a sorted array. For example, enter the sorted array {1, 2, 3, 3, 3, 3, 3, 4, 5} and the number 3. Since 3 appears 4 times in this array, output 4.
function getNumFindCount(array,num){
let count=0
(item => {
if(item==num)count++
});
return count
}
let count=getNumFindCount([1,2,3,3,3,4,5],3)
(count);
Topic XXIX: Numbers appearing only once in an array: All but two numbers in an integer array appear twice. Write a program to find the two numbers that appear only once.
function getOnlyOneNum(array) {
// Because new Set returns an object Set([1,2,...]) after de-duplication, it has to be converted to an array. , so we need to convert to an array
let numList = (new Set(array))
let onlyOneList = []
(item => {
let count = 0
(item2 => {
if (item2 == item) count++
})
if (count == 1) (item)
})
(onlyOneList);
}
getOnlyOneNum([1, 2, 2, 3, 3, 4])
Topic 30: Sequences of consecutive positive numbers with sum S: Ming likes math very much. One day when he was doing his math homework, he was asked to calculate the sum of 9~16, and he wrote out the correct answer of 100 right away. but he was not satisfied with that, he was wondering how many sequences of consecutive positive numbers with sum 100 (including at least two numbers) there are. It didn't take him long to get another sequence of consecutive positive numbers that sum to 100: 18,19,20,21,22. Now the question is put to you, can you also quickly find all the consecutive positive sequences that sum to S. Good Luck! The order within the sequence is from smallest to largest, and the order between the sequences is from smallest to largest starting number.
function getTotalNum(sum) {
if (sum < 2) return [];
var result = [];
var a = 0, b = 0, total = 0;
while (a <= (sum / 2)) {
if (total < sum) {
b++;
total += b;
} else if (total > sum) {
total -= a
a++;
} else {
var temp = [];
for (var i = a; i <= b; i++) {
(i)
}
(temp)
if (a + 1 < b) {
total -= a;
a++
} else {
break;
}
}
}
return result;
}
let list=getTotalNum(100)
(list);
Topic XXXI: Two numbers with sum S: Input an incrementally sorted array and a number S. Find two numbers in the array, yes their sum is exactly S. If there are more than one pair of numbers whose sum is equal to S, output the smallest product of the two numbers. Output description: corresponding to each test case, output two numbers, smallest first.
function totaleqNum(array, sum) {
let list = []
for (let i = 0; i < ; i++) {
for (let j = i + 1; j < ; j++) {
if (array[i] + array[j] == sum) {
let data = {
list: [array[i], array[j]],
result: array[i] * array[j]
}
(data)
}
}
}
if ( > 1) {
let min = list[0].result
(item => {
if ( < min) {
return
}
})
return list[0].list
}
return list[0].list
}
let result=totaleqNum([1, 2, 3, 4, 5, 6], 5)
(result);
Topic XXXII: Rotating a String Left: There is a shift instruction in assembly language called cyclic left shift (ROL), and now there is a simple task to simulate the result of this instruction in a string. For a given sequence of characters S, you are asked to output the sequence after a cyclic left shift of K bits. For example, the character sequence S="abcXYZdef", you are asked to output the result after a cyclic left shift of 3 bits, i.e. "XYZdefabc".
function transformStr(str,left){
if(left>){
return 'The length of the displacement must not exceed the length of the character'
}
let leftStr=(left,)
let rightStr=(0,left)
return leftStr+rightStr
}
let newStr=transformStr('hello',2)
(newStr);
Topic 33: Flipping Word Order Columns: A new employee, Fish, has recently come to Cowcatcher. Every morning, he always takes an English magazine and writes some sentences in his notebook. Cat, a colleague, is quite interested in what Fish writes. One day he borrowed it from Fish, but he couldn't understand what it meant. For example, "student. a am I". Then he realized that he had reversed the order of the words in the sentence, and the correct sentence should be "I am a student." Cat is not very good at reversing the order of the words one by one, can you help him?
Idea: split the string into an array according to the space separation, and then reverse reverse the array, and finally join merge into a string
function revolveStr(str){
return newStrList=(" ").reverse().join(" ")
}
let newStr=revolveStr("I am a student.")
(newStr);
Topic XXXIV: 1+2+3+... +n: Find 1+2+3+... +n, requires that multiplication and division, keywords such as for, while, if, else, switch, case, and conditional judgment statements (A?B:C) cannot be used.
function totalNum(n){
var sum=n;
var a=(n>0)&&((sum+=totalNum(n-1))>0)
return sum
}
let total=totalNum(3)
(total);
Topic XXXV: Convert a string to an integer. Converting a string to an integer requires that no string-to-integer library function be used. Returns 0 if the number is 0 or if the string is not a legal numeric value. input description: input a string, including numeric symbols, can be empty. Output description: if it is a legal numeric expression, then return the number, otherwise return 0.
Idea: Loop the string, determine whether each character is a number, because you can not use the string to convert the integer library function, so you have to define a function to determine whether the string is between 0 ~ 9, is that is a number.
function strToNumber(str){
let newStr=''
for (let i = 0; i < ; i++) {
if(isNumber(str[i])){
newStr+=str[i]
}
}
return newStr
}
function isNumber(data){
if(data>=0 || data<=9){
return true
}
return false
}
let newStr=strToNumber('+2147#48^3647')
(newStr);
Topic XXXVI: Repeated Numbers in Arrays: All numbers in an array of length n are in the range 0 to n-1. Some numbers in the array are repeated, but it is not known how many numbers are repeated or how many times each number is repeated. Find any one repeated number in the array.
The idea is to use set to de-emphasize the array, then traverse the array, and then traverse the original array to find the first duplicate number in the array, and randomly try catch to throw an exception to interrupt the traversal and return
function searchFirstFindTwoNum(array) {
try {
(new Set(array)).forEach(item => {
let count = 0
(item2 => {
if (item == item2) count++
if (count > 1) throw new Error(item)
})
})
} catch (e) {
return
}
return 'No duplicate numbers in the array'
}
let number = searchFirstFindTwoNum([1, 2, 3, 3, 4, 5])
(number);
Topic XXXVII: Constructing product arrays: Given an array A[0,1,... ,n-1], construct an array B[0,1,... ,n-1], where the element B[i]=A[0] in BA[1]...A[i-1]A[i+1]...A[n-1]. Division cannot be used.
function getTotalList(array) {
let newArray = []
for (let i = 0; i < ; i++) {
newArray[i] = getTotal(array) * array[i-1]-array[i+1]
(newArray[i]);
}
return newArray
}
function getTotal(array) {
let total = 1;
(item => total *= item);
return total
}
let newArray = getTotalList([2, 4, 6, 7, 8])
(newArray);
Topic XXXVIII: First non-repeating character in a character stream: Please implement a function to find the first character that occurs only once in a character stream. For example, when only the first two characters "go" are read from the stream, the first character that occurs only once is "g". When the first six characters "google" are read from the stream, the first character that occurs only once is "l". Output description: if no character that occurs once exists in the current character stream, the # character is returned.
Idea: first de-emphasis of the original array to obtain a list of characters, followed by a single occurrence of words to give a default value for the first character, to facilitate the subsequent judgment, the first traversal after the de-emphasis of the character array, according to each character of the original string traversal query is repeated, if there is a repetition of repeated words and a single occurrence of characters is inconsistent with the proof of the emergence of the first single character, the end of an exception is thrown to the end of the traversal and return when the duplicate single occurrence of characters for the current character, if so, it means that there is no single character in front, and determine whether the current position has been traversed to the end of the most, if not to continue the traversal of the next character, if the current position is the penultimate position of the string, the next character must be a single occurrence of the word, then return directly.
function searchFirstFindOneStr(str) {
try {
let array = (new Set(("")))
let keyword = array[0]
(item => {
let count = 0
for (let i = 0; i < ; i++) {
if (item == str[i]) count++
if (count > 1 && keyword != str[i]) throw new Error(keyword)
if (count > 1 && keyword == str[i]) {
count = 0
if (i < -1 && i < - 2) keyword = str[i + 1]
if (i == - 2) throw new Error(str[ - 1])
}
}
})
} catch (e) {
return
}
return '#'
}
let str = searchFirstFindOneStr("hheello66")
(str);
Topic XXXIX: Median in a data stream (to be understood in depth): How to get the median in a data stream? If an odd number of values are read from the data stream, then the median is the value in the middle of all the values after sorting. 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 values are sorted.
function getCenterNum(array){ //[1,2,3,4,5]
let index=(/2)
let newArray=()
if(%2==0){
return (newArray[index-1]+newArray[index])/2
}else{
return newArray[index]
}
}
let num=getCenterNum([3,2,3,7,5,6])
(num);
Topic 40: Maximum values in sliding windows (to be understood in depth): Given an array and the size of a sliding window, find the maximum of all the values in the sliding window. For example, if you enter the array {2,3,4,2,6,2,5,1} and the size of the sliding window 3, then there are 6 sliding windows, and their maximum values are {4,4,6,6,6,5};
reasoning:array{2,3,4,2,6,2,5,1}The sliding windows are the following 6 classifier for individual things or people, general, catch-all classifier: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5 ],1}, {2,3,4,2,6,[2,5,1]}.
The maximum value is the largest of the elements in each window [2,3,4],[3,4,2],[4,2,6],[2,6,2],[6,2,5],[2,5,1], respectively, i.e., it is the one with the largest element, i.e., it is the one with the largest element, i.e., it is the one with the largest element in the window [4,4,6,6,6,6,5].
function slideWindowMax(array,size){
let allWindows=[],allMax=[]
while(>=size){
((0,size))
array=(1,)
}
(i => {
let max=i[0]
(j=>{
if(j>max)max=j
})
(max)
});
return allMax
}
let maxList=slideWindowMax([2,3,4,2,6,2,5,1],3)
(maxList);
The above is a personal study to organize the content, the level is limited, if there is any error, I hope you gardeners do not begrudge advice! If you think it's good, please support it with a like and a follow! Thank you~๑-́₃-̀๑ \❀❀❀❀❀❀❀❀❀❀❀