最近练习了一些前端算法题,现在做个总结,以下题目都是个人写法,并不是标准答案,如有错误欢迎指出,有对某道题有新的想法的友友也可以在评论区发表想法,互相学习🤭
function sortList(array, num) {
// 解法一.循环indexOf查询 有返回下标,没有则返回-1
// for (let i = 0; i < array.length; i++) {
// if (array[i].indexOf(num) != -1) {
// return console.log('有');
// }
// }
// 解法二.嵌套循环
// for(let i=0;i<array.length;i++){
// for(let j=0;j<array[i].length;j++){
// if(array[i][j]==num){
// return '有'
// }
// }
// }
// 解法三.数组扁平化,然后indexOf查找
let newArray = toStr(array)
console.log(newArray)
if (newArray.indexOf(num) != -1) {
return console.log('有');
}
return console.log('没有');
}
// 数组扁平化
function toStr(arr) {
return arr.toString().split(',').map(item => {
return Number(item)
})
}
let ary = [[1, 2, 3, 4], [2, 3, 4, 5]]
sortList(ary, 5)
function replaceSpace(str) {
// 解法一:暴力for循环对比
// let newStr=''
// for(let i=0;i<str.length;i++){
// if(str[i]==' '){
// newStr+='%20'
// }else{
// newStr+=str[i]
// }
// }
// console.log(newStr)
// return newStr
// 解法二:split分割成数组,再进行join转字符串
// let newStr = str.split分割成数组,再进行join转字符串(" ").join("%20");
// console.log(newStr)
// return newStr
// 解法三:正则
// var reg = / /g;
// let newStr=str.replace(reg, "%20");
// console.log(newStr)
// return newStr
}
replaceSpace('We Are Happy')
思路,利用栈的特性先进后出,模拟压栈,然后再进行出栈实现
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
function printNode(node) {
console.log(node)
// 压栈实现
let stock = new Array()
let NodeNextElm = node
while (NodeNextElm !== null) {
// console.log(stock)
stock.push(NodeNextElm.data)
NodeNextElm = NodeNextElm.next
}
while (stock.length > 0) {
console.log(stock.pop())
}
}
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
node1.next = node2
node2.next = node3
printNode(node1)
一.
①[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]) 根节点 1 ,有左右节点
二.
①L([2,4,7],[4,7,2])-> val=>2 ->L([4,7],[4,7]) && R(null , null) 根节点2(属1的左节点) ,有左节点,无右节点
②R([3,5,6,8],[5,3,8,6])-> val=>3 ->L([5],[5]) && R([6,8],[6,8]) 根节点3(属1的右节点) ,有左右节点
三.
①L([4,7],[4,7]) ->val=>4 -> L(null , null) && R([7],[7]) 根节点4(属2的左节点) ,有右节点,无左节点
②R([6,8],[8,6]) -> val=>6 -> L([8] , [8]) && R(null , null) 根节点6(属3的右节点),有左节点,无右节点
③L([5],[5]) -> val=>5->(null,null)->终止 尾节点5(属3的左节点)
四.
①R([7],[7]) -> val=>7 ->终止 尾节点7(属4的右节点)
②L([8],[8]) -> val=>8 ->终止 尾节点8(属6的左节点)
function rebuildBinaryTree(front, centre) {
if (!front || front.length == 0) {
return null;
}
var TreeNode = {
val: front[0]
};
for (var i = 0; i < front.length; i++) {
//找到中序遍历根节点位置
if (centre[i] === front[0]) {
//对于中序遍历,根节点左边的节点位于二叉树的左边,根节点右边的节点位于二叉树的右边
TreeNode.left = rebuildBinaryTree(front.slice(1, i + 1), centre.slice(0, i));
TreeNode.right = rebuildBinaryTree(front.slice(i + 1), centre.slice(i + 1));
}
}
return TreeNode;
}
let tree = rebuildBinaryTree([1, 2, 4, 7, 3, 5, 6, 8], [4, 7, 2, 1, 5, 3, 8, 6])
console.log(tree)
思路:使用两个数组模拟栈,一个用于push一个用于pop
let stack_push = []
let stack_pop = []
function pushData(data) {
stack_push.push(data)
}
function popData() {
if (stack_pop.length > 0) {
console.log(stack_pop.pop())
} else {
if (stack_push.length > 0) {
while (stack_push.length > 0) {
stack_pop.push(stack_push.pop())
}
console.log(stack_pop.pop());
} else {
console.log('队列为空');
}
}
}
pushData(1)
pushData(2)
pushData(3)
pushData(4)
console.log(stack_push);
console.log(stack_pop);
popData()
console.log(stack_push);
console.log(stack_pop);
pushData(5)
console.log(stack_push);
console.log(stack_pop);
popData()
popData()
popData()
popData()
popData()
console.log(stack_push);
console.log(stack_pop);
function revoleArray(array) {
let min = array[0];
let index = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i]
index = i
}
}
let newArray = array.slice(0, index)
let newArray2 = array.slice(index)
return newArray2.concat(newArray)
}
let newArray = revoleArray([3, 4, 5, 1, 2])
console.log(newArray)
思路:斐波那契数列:[1,1,2,3,5,8,13,...] 每个数等于前两个数之和
//解法一:递归
function fbnq(n) {
if (n <= 1) {
return 1
}
return fbnq(n - 1) + fbnq(n - 2)
}
// 解法二:循环
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
List.push(result)
}
return List[n]
}
}
let a = fbnq(5)
console.log(a);
let b = Fibonacci(5)
console.log(b);
思路:jump(1)=1 jump(2)=2 jump(3)=3 jump(4)=5 jump(5)=8 类似于斐波那契数列只不过就是前两项变为1,2
function jump(n){
if(n<=2){
return n;
}
return jump(n-1) + jump(n-2)
}
let jumpNum=jump(5)
console.log(jumpNum);
思路:jump(1)=1 jump(2)=2 jump(3)=4 jump(4)=8 2的n次方
function btJump(n){
// 解法一:用位运算符 2的n次方最简单就是用位运算符 1<<n(将1左移n位数) 1:0001 2:0010 4:0100 8:1000
// return 1<<(--n);
// 解法二:递归
if(n<=1){
return n
}else{
return 2*btJump(n-1)
}
}
let jumpNum=btJump(5)
console.log(jumpNum);
function rectCover(number) {
if (number <= 2) {
return number;
} else {
return rectCover(number - 1) + rectCover(number - 2);
}
}
let rectNum=rectCover(4)
console.log(rectNum);
思路:一、使用split('')将其转换为字符数组然后reduce进行累加 二、暴力for循环判断
function countOneNum(num) {
let count=0;
// toString(2)转化为二进制
// 解法一:使用split('')将其转换为字符数组然后reduce进行累加
count = num.toString(2).split('').reduce((acc, cur) => {
console.log(acc, cur)
return acc + parseInt(cur)
}, 0);
let Binary=num.toString(2)
// 解法二:for循环
for(let i=0;i<Binary.length;i++){
if(Binary[i]==1)count++
}
return count
}
let count = countOneNum(5)
console.log(count);
function md(base,exponent){
if(exponent<0){
if(base<0){
return '我也不知道怎么变负数'
}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)
console.log(total);
思路:循环找出奇偶列表,然后concat合并
function changeArray(array) {
let jList = [], oList = []
array.forEach(item => {
if (item % 2 == 0) {
oList.push(item)
} else {
jList.push(item)
}
});
return jList.concat(oList)
}
let NewArray = changeArray([2, 3, 4, 5, 9, 8, 7])
console.log(NewArray);
思路:模拟栈将链表push进栈,随后判断k是否大于等于链表的长度,反转数组再取出下标为k-1的节点
class Node{
constructor(data){
this.data=data
this.next=null
}
}
function getIndexNode(node,index){
let stack=[]
let nextNodeElm=node
while(nextNodeElm!=null){
stack.push(nextNodeElm.data)
nextNodeElm=nextNodeElm.next
}
if(stack.length<index){
return '输入的节点请小于等于链表长度'
}
stack.reverse()
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)
node1.next=node2
node2.next=node3
node3.next=node4
node4.next=node5
let node=getIndexNode(node1,5)
console.log(node)
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
function revolveNode(node) {
if (node == null) {
return false;
}
let p1 = node, p2 = null, temp = null;
while (p1) {
temp = p1.next;
p1.next = 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)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
let node = revolveNode(node1)
console.log(node)
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
function Merge(node1, node2) {
console.log(node1, node2);
if (node1 == null) {
return node2;
} else if (node2 == null) {
return node1;
}
var result = {};
if (node1.data < node2.data) {
result = node1;
result.next = Merge(node1.next, node2);
} else {
result = node2;
result.next = Merge(node1, node2.next);
}
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)
node1.next = node2
node2.next = node3
node3.next = node5
node4.next = node6
node5.next = node7
node6.next = node8
node8.next = node9
node9.next = node10
let newNode=Merge(node1,node4)
console.log(newNode);
例如,如果输入如下矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
思路:依次顺序打印出第一行,然后逆时针旋转矩阵,继续打印第一行,直到完成
function rotateMatrix90Clockwise(matrix) {
const numRows = matrix.length;
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=array.slice(0,1)[0]
// console.log(list);
let newList=list.reverse()
while(newList.length>0){
console.log(newList.pop())
}
// console.log(newList);
array=array.slice(1,)
if(array.length==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);
let stack_push = []
let stack_pop = []
function pushData(data) {
stack_push.push(data)
}
function popData() {
if (stack_pop.length > 0) {
console.log(stack_pop.pop());
} else {
if (stack_push.length > 0) {
while (stack_push.length > 0) {
stack_pop.push(stack_push.pop())
}
console.log(stack_pop.pop());
} else {
console.log('空栈')
}
}
}
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()
console.log(min);
例如:序列 1,2,3,4,5 是某栈的压入顺序,序列 4,5,3,2,1 是该压栈序列对应的一个弹出序列,但 4,3,5,1,2 就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:一、模拟压栈弹栈 二、直接反转数组进行pop比较
let stack_push = []
let stack_pop = []
function pushData(data) {
stack_push.push(data)
}
function popData() {
if (stack_pop.length > 0) {
console.log(stack_pop.pop());
} else {
if (stack_push.length > 0) {
while (stack_push.length > 0) {
stack_pop.push(stack_push.pop())
}
console.log(stack_pop.pop());
} else {
console.log('空栈')
}
}
}
function testStack(pushStack,popStack){
// 解法一:模拟压栈弹栈
// if(pushStack.length != popStack.length){
// return '不是'
// }
// let NewPushStack=pushStack.reverse()
// let NewPopStack=popStack.reverse()
// while(NewPushStack.length>0){
// pushData(NewPushStack.pop())
// }
// while(stack_push.length>0){
// if(stack_push.pop() != NewPopStack.pop())return '不对'
// }
// return '正确'
// 解法二:直接反转数组进行pop比较
if(pushStack.length != popStack.length){
return '不是'
}
let NewPopStack=popStack.reverse()
while(pushStack.length>0){
if(pushStack.pop() != NewPopStack.pop())return '不对'
}
return '正确'
}
let result=testStack([1,2,3,4,5],[5,4,3,2,1])
console.log(result);
function copyNode(pHead){
console.log(pHead)
if (!pHead) {
return null;
}
// 复制头结点
var node = new Node(pHead.data);
node.other = pHead.other;
// 递归其他节点
node.next = copyNode(pHead.next);
return node;
}
class Node {
constructor(data) {
this.data = data
this.next = null
this.other = null
}
}
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
node1.next = node2
node2.next = node3
node1.other = node2
node2.other = node3
node3.other = node1
let newNode=copyNode(node1)
console.log(newNode);
function permute(str, left = 0, right = str.length - 1) { //abc left 2
console.log(left,right)
// 如果左边界等于右边界,说明只剩下一个字符,打印它
if (left === right) {
console.log("结果:",str);
} else {
// 遍历从l到r的每个位置
for (let i = left; i <= right; i++) {
// 将当前位置i的字符与左边界l的字符交换
str = swap(str, left, i);
console.log("str:",str,"left:",left,"I:",i);
// 递归地对剩余的子字符串进行排列(注意left+1表示排除已固定的字符)
permute(str, left + 1, right);
// 递归返回后,需要将字符交换回原来的位置,以便下一次循环使用原始字符串
str = swap(str, left, i);
}
}
}
function swap(str, i, j) {
// 将字符串转换为字符数组
let arr = str.split('');
// 解构交换元素
[arr[i], arr[j]] = [arr[j], arr[i]];
// 将修改后的数组转换回字符串
return arr.join('');
}
permute('abc');
function moreAHalfNum(array){
let length=array.length
let maxLength=Math.floor(length/2)
let computedTotal={}
let maxNum=null
array.forEach(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])
console.log(num);
思路:先sort排序,此时数组是从小到大排序,取前k个即可
function searchMinCountNum(array,K){
let NewArray=array.sort()
return NewArray.slice(0,K)
}
let countNum=searchMinCountNum([2,1,8,9,6,5],3)
console.log(countNum);
function PrintMinNumber(numbers) {
numbers.sort(function (a, b) {
var s1 = a + '' + b;
var s2 = b + '' + a;
for (var i = 0; i < s1.length; i++) {
if (s1.charAt(i) > s2.charAt(i)) {
return 1
} else if (s1.charAt(i) < s2.charAt(i)) {
return -1;
}
}
return 1
})
console.log(numbers);
var result = "";
numbers.map(function (num) {
result = result.concat(num)
})
return result;
}
let num=PrintMinNumber([32,3,321])
console.log(num);
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] = Math.min(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++;
}
console.log(uglys);
return uglys[index - 1]
}
let count=getUglyNumberSolution(11)
console.log(count);
function getFirstChar(str){
str=str.toUpperCase()
let chat={}
for (let i = 0; i < str.length; i++) {
if(chat[str[i]]){
chat[str[i]]++
}else{
chat[str[i]]=1
}
}
console.log(chat);
for (let i = 0; i <= str.length; i++) {
if(chat[str[i]]==1){
return str.indexOf(str[i]) +"=>"+str[i]
}
}
return '无只出现一次的字符'
}
let index=getFirstChar('hheello')
console.log(index);
function getReverseNum(array){
let count=0
let towNum=[]
if(array.length>1){
towNum=array.slice(0,2)
console.log(towNum);
if(towNum[0]>towNum[1]){
count++
}
return count + getReverseNum(array.slice(2,))
}
return count
}
let num=getReverseNum([2,1,3,4,5,4,5,4,5,4,5,4])
console.log(num);
function getNumFindCount(array,num){
let count=0
array.forEach(item => {
if(item==num)count++
});
return count
}
let count=getNumFindCount([1,2,3,3,3,4,5],3)
console.log(count);
function getOnlyOneNum(array) {
// 因为new Set去重后返回的是一个对象Set([1,2,...]),所以要用Array.from转换为数组
let numList = Array.from(new Set(array))
let onlyOneList = []
numList.forEach(item => {
let count = 0
array.forEach(item2 => {
if (item2 == item) count++
})
if (count == 1) onlyOneList.push(item)
})
console.log(onlyOneList);
}
getOnlyOneNum([1, 2, 2, 3, 3, 4])
function getTotalNum(sum) {
if (sum < 2) return [];
var result = [];
var a = 0, b = 0, total = 0;
while (a <= Math.floor(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++) {
temp.push(i)
}
result.push(temp)
if (a + 1 < b) {
total -= a;
a++
} else {
break;
}
}
}
return result;
}
let list=getTotalNum(100)
console.log(list);
function totaleqNum(array, sum) {
let list = []
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == sum) {
let data = {
list: [array[i], array[j]],
result: array[i] * array[j]
}
list.push(data)
}
}
}
if (list.length > 1) {
let min = list[0].result
list.forEach(item => {
if (item.result < min) {
return item.list
}
})
return list[0].list
}
return list[0].list
}
let result=totaleqNum([1, 2, 3, 4, 5, 6], 5)
console.log(result);
function transformStr(str,left){
if(left>str.length){
return '位移长度不能超过字符长度'
}
let leftStr=str.slice(left,)
let rightStr=str.slice(0,left)
return leftStr+rightStr
}
let newStr=transformStr('hello',2)
console.log(newStr);
思路:split对字符串按照空格分隔成数组,然后reverse反转数组,最后join合并成字符串
function revolveStr(str){
return newStrList=str.split(" ").reverse().join(" ")
}
let newStr=revolveStr("I am a student.")
console.log(newStr);
function totalNum(n){
var sum=n;
var a=(n>0)&&((sum+=totalNum(n-1))>0)
return sum
}
let total=totalNum(3)
console.log(total);
思路:循环字符串,判断每个字符是否为数字,因为不能使用字符串转换整数的库函数,所以要定义一个函数判断字符串是否在0~9之间,是即为数字。
function strToNumber(str){
let newStr=''
for (let i = 0; i < str.length; 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')
console.log(newStr);
思路,使用set对数组进行去重,然后对数组进行遍历,再去遍历原数组,找出数组里第一个出现重复数字,随机try catch抛出异常进行中断遍历并进行返回
function searchFirstFindTwoNum(array) {
try {
Array.from(new Set(array)).forEach(item => {
let count = 0
array.forEach(item2 => {
if (item == item2) count++
if (count > 1) throw new Error(item)
})
})
} catch (e) {
return e.message
}
return '数组内无重复数字'
}
let number = searchFirstFindTwoNum([1, 2, 3, 3, 4, 5])
console.log(number);
function getTotalList(array) {
let newArray = []
for (let i = 0; i < array.length; i++) {
newArray[i] = getTotal(array) * array[i-1]-array[i+1]
console.log(newArray[i]);
}
return newArray
}
function getTotal(array) {
let total = 1;
array.forEach(item => total *= item);
return total
}
let newArray = getTotalList([2, 4, 6, 7, 8])
console.log(newArray);
思路:先对原数组进行去重获取字符列表,随后单个出现单词给个默认值为首个字符,方便后续判断,首先遍历去重后的字符数组,根据每个字符对原字符串进行遍历查询是否重复,如果出现重复且重复词与单个出现字符不一致,则证明出现首个单一字符,则抛出异常结束遍历并返回,当重复时单个出现字符为当前字符,如果是则表示前面并无单一字符,并判断当前位置是否已经遍历到最末端了,如果不是继续下一个字符的遍历,如果当前位置为字符串倒数第二的位置,则下一个字符必定为单一出现单词,则直接返回。
function searchFirstFindOneStr(str) {
try {
let array = Array.from(new Set(str.split("")))
let keyword = array[0]
array.forEach(item => {
let count = 0
for (let i = 0; i < str.length; 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 < str.length-1 && i < str.length - 2) keyword = str[i + 1]
if (i == str.length - 2) throw new Error(str[str.length - 1])
}
}
})
} catch (e) {
return e.message
}
return '#'
}
let str = searchFirstFindOneStr("hheello66")
console.log(str);
function getCenterNum(array){ //[1,2,3,4,5]
let index=Math.floor(array.length/2)
let newArray=array.sort()
if(newArray.length%2==0){
return (newArray[index-1]+newArray[index])/2
}else{
return newArray[index]
}
}
let num=getCenterNum([3,2,3,7,5,6])
console.log(num);
思路:针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下 6 个: {[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]}。
最大值分别就是每个窗口[2,3,4],[3,4,2],[4,2,6],[2,6,2],[6,2,5],[2,5,1]中元素最大的一个,即为[4,4,6,6,6,5]
function slideWindowMax(array,size){
let allWindows=[],allMax=[]
while(array.length>=size){
allWindows.push(array.slice(0,size))
array=array.slice(1,)
}
allWindows.forEach(i => {
let max=i[0]
i.forEach(j=>{
if(j>max)max=j
})
allMax.push(max)
});
return allMax
}
let maxList=slideWindowMax([2,3,4,2,6,2,5,1],3)
console.log(maxList);
上述为个人学习整理内容,水平有限,如有错误之处,望各位园友不吝赐教!如果觉得不错,请点个赞和关注支持一下!谢谢~๑•́₃•̀๑ \❀❀❀