面试遇到的算法问题

美团面试

1. 城市a到城市e有多少条路径问题。

a>b>c>e

a>b>f>e

a>k>e

...

class Node{

constructor(address) {

this.address = address

this.path = []

}

}

let bj = new Node('北京')

let tj = new Node('天津')

let hn = new Node('河南')

bj.path.push(tj)

bj.path.push(hn)

let sd = new Node('山东')

let sh = new Node('上海')

tj.path.push(sd)

sd.path.push(sh)

hn.path.push(sh)

let pathAll = []

function getPath(path, arr) {

let len = path.length, item, info

for (;len--;) {

item = path[len]

info = [...arr, item.address]

if (item.path.length) {

getPath(item.path, info)

} else {

pathAll.push(info)

}

}

}

getPath(bj.path, [bj.address])

console.log(pathAll)

滴滴面试

1. 用栈的方法判断一组括号是否闭合

function isBrackets(str) {

let arr = str.split('')

let type = ['()', '[]', '{}']

let _arr = []

let _i, _j

while(arr.length) {

_i = arr.pop()

_j = _arr.pop()

if (!~type.indexOf(_i + _j)) {

_j && _arr.push(_j)

_i && _arr.push(_i)

}

}

return !_arr.length

}

console.log(isBrackets('[{{}{}}]'))

console.log(isBrackets('[{{}}[]'))

百融金服面试

1.边长为1的四个正方形(2x2)组成的大正方形有5个正方形,边长为1的16(4x4)个正方形组成的大正方形有30个正方形,求公式。

四个正方形:2 * 2 (边长为1的正方形)+ 1 (边长为2的正方形)

十六个正方形:4*4(边长为1的正方形)+3*3(边长为2的正方形)+2*2(边长为3的正方形)+1*1(边长为4的正方形)

猜你喜欢

转载自blog.csdn.net/zsnpromsie/article/details/85967007
今日推荐