前言
现在IT市场面试,上来就是做题,本篇是小编最近面试总结的一些手写题;
查找单词返回下标
//根据开头和结尾字母返回对应单词下标,如果查找到多个就返回最后一个,没有返回null;
const list = ['red', 'apple', 'green', 'rsxd'];
function Fun(arr) {
const workList = (a, b) => {
const newArr = arr.filter(item => {
return item.split('')[0] === a && item.split('')[item.length - 1] === b;
})
const index = arr?.indexOf(newArr[newArr?.length - 1])
return index !== -1 ? index : null;
}
return {
workList
}
}
const newFun = new Fun(list);
console.log(newFun.workList('r', 'd'))//3
双指针
//返回数组就两数之和等于target 的下标
function DoublePointer(list, target) {
let firstIndex = 0;
let endIndex = list.length - 1;
while (firstIndex < endIndex) {
if (list[firstIndex] + list[endIndex] === target) {
return [firstIndex, endIndex]
} else if (list[firstIndex] + list[endIndex] > target) {
endIndex--;
} else {
firstIndex++;
}
}
}
console.log(DoublePointer([2, 3, 4, 7, 9], 6)) // [0,2]
二分查找
function binarySearch (arr, key){
let low = 0, high=arr.length-1;
while(low<high){
let mid = parseInt(low + (high-lov)/2);
if(key === arr[mid]){
return mid;
}else if(key > arr[mid]){
high = mid -1;
}else{
return -1
}
}
}
console.log(binarySearch([1,2,3,4],3)) //返回索引 2
查找字符串中最长的子串
//求一个字符串的最长不重复子串 给定"abcabcabcbb"的答案是"abc" 给定"120135435"答案是"201354"
const filterStr = (s) => {
// eslint-disable-next-line prefer-const
let arr = [], result = [];
for (let i = 0; i < s.length; i++) {
const index = arr.indexOf(s[i])
if (index !== -1) {
arr.splice(0, index + 1);
}
arr.push(s[i])
result.push(Object.assign([], arr));
}
return result;
}
const fn = function (arr) {
let long = 0
let value = '';
for (let i = 0; i < arr.length; i++) {
const temp = arr[i].length
if (temp >= long) {
long = temp
value = arr[i]
}
}
return value;
}
const str = JSON.parse(JSON.stringify(fn(filterStr('120135435'))));
console.log(str.join(''))//201354
字符串压缩
const str = 'aaaaaabcc';
function Fun(strs) {
let result = "";
let count = 0;
let num = strs[0];
strs.split('').forEach((ele) => {
if (num === ele) {
count++;
} else {
result += count + num;//字符串拼接
count = 1;
num = ele;
}
});
result += count + num;
return result.length >= strs.length ? strs : result;
}
console.log(Fun(str))//6a1b2c
字符串中元音字母反序
function vowelReverse(str) {
const vowel = ['a', 'e', 'i', 'o', 'u'];
const list = str.split('').filter(item => vowel.includes(item)).reverse();
return str.split('').map(item => {
if (vowel.includes(item)) {
const ele = list[0];
list.shift();
return ele;
}
return item;
}).join('');
}
console.log(vowelReverse('hellou')) // hulloe
数字三位逗号分隔
function getNum(str) {
return Number(str.replace(/[^\d]/g, '')).toLocaleString();
}
console.log(getNum('7#76@23$2@3#')) //7,762,323
取两个数组中共同出现的值
const maps = (list) => {
const map = new Map();
list.forEach(item => {
const count = map.get(item);
if (count) {
map.set(item, count + 1)
} else {
map.set(item, 1)
}
});
return map;
}
const filterList = (x, y) => {
const xMap = maps(x);
const yMap = maps(y);
let result = [];
xMap.keys().forEach(item => {
const xEle = xMap.get(item);
const yEle = yMap.get(item);
const ele = Math.min(xEle, yEle);
for (let i = 0; i < ele; i++) {
result.push(item);
}
});
return result;
}
console.log(filterList([1, 2, 2], [2, 2, 2, 3])) // [2 2]
获取字符串中重复相邻的单词
// jack jack no no jack Jack = 3
// jack jack Jack Jack = 1
function adjacentWord(str) {
const list = str.split(' ').filter(item => item);
let result = [];
let count = 0;
list.reduce((pre, cur) => {
if (pre.toLowerCase() === cur.toLowerCase()) {
count += 1
} else {
count && result.push(count);
count = 0;
}
return cur;
}, '')
count && result.push(count);
return result.length;
}
console.log(adjacentWord('jack jack no no jack Jack'))//3
判断两个字符串结构是否相等
function strFlag(s, t) {
const sLen = s.length;
const tLen = t.length;
if (sLen !== tLen) {
return false;
}
let obj: any = {};
for (let i = 0; i < sLen; i++) {
const currentS = s[i];
const CurrentT = t[i];
obj[currentS] ? obj[currentS] += 1 : obj[currentS] = 1;
obj[CurrentT] ? obj[CurrentT] -= 1 : obj[CurrentT] = -1;
}
console.log(obj)
return Object.values(obj).every(item => item === 0);
}
console.log(strFlag('abc', 'bca')) //true
封装promise.all
function promiseAll(promises) {
return new Promise((resolve, reject) => {
let result = [];
let count = 0;
const len = promises.length;
promises.forEach((item, index) => {
Promise.resolve(item).then(res => {
count += 1;
result.push(res);
if (len === count) {
resolve(result);
}
}).catch(reject);
});
})
}
let p1 = new Promise((resolve) => resolve(1));
let p2 = new Promise((resolve) => resolve(2));
let p3 = new Promise((resolve) => resolve(5));
promiseAll([p1, p2, p3]).then(res => {
console.log(res)//1,2,5
})
防抖
function debounce(fn, delay) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay)
}
}
节流
function throttle(fn, delay) {
let timer;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay)
}
}
}