题目描述
我做的:
function foo(arg){
let arr = arg;
let temp = [];
arr.map(item => {
temp.push(item.split(' ')[0])
})
let obj = {}
for(let i=0;i<temp.length;i++){
obj[temp[i]] = obj[temp[i]] ? (obj[temp[i]]+1) : 1
}
const newArr = []
while(arr.length){
let maxName = Object.keys(obj)[0];
let maxVal = obj[maxName];
for(let i in obj){
if(maxVal < obj[i]){
maxVal = obj[i]
maxName = i
}
}
while(temp.includes(maxName)){
let idx = temp.indexOf(maxName)
temp.splice(idx,1)
newArr.push(...arr.splice(idx,1))
}
delete obj[maxName]
}
return newArr
}
foo(['ZHANG SAN','LI SI','WANG WU','WANG LIU','WANG QI','ZHANG WU','LI LIU'])
我家小哥做的:
function f(list) {
list = list.map(x=>x.split(' '))
let countMap = {}
for (let i=0; i<list.length; i++) {
if (countMap[list[i][0]]) {
countMap[list[i][0]] += 1
} else {
countMap[list[i][0]] = 1
}
}
list = list.sort((x,y)=>{return countMap[y[0]]-countMap[x[0]]})
return list.map(x=>x.join(' '))
}
f(['ZHANG SAN','LI SI','WANG WU','WANG LIU','WANG QI','ZHANG WU','LI LIU'])
将问题复杂化了,还得好好多学习,加油!!!