Last active
November 5, 2020 12:12
-
-
Save luojiyin1987/c5a2a8004fea01996210bb47044517b8 to your computer and use it in GitHub Desktop.
sort 排序的强化,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {string[]} votes | |
| * @return {string} | |
| */ | |
| var rankTeams = function(votes) { | |
| if(votes.length ===1 ) { | |
| return votes[0]; | |
| } | |
| const teams = votes[0].length; | |
| const obj = {}; | |
| for(let i=0; i< votes.length; i++) { | |
| for(let j=0; j<teams; j++) { | |
| if(!obj[votes[i][j]]){ | |
| obj[votes[i][j]] = new Array(votes.length).fill(0); | |
| } | |
| obj[votes[i][j]][j]+=1 | |
| } | |
| } | |
| //console.log("obj", obj); | |
| const res = Object.keys(obj).sort((a,b)=>{ | |
| const listA = obj[a]; | |
| const listB = obj[b]; | |
| for(let i=0; i<votes[0].length; i++) { | |
| if(listA[i] !== listB[i]) { | |
| return listB[i] -listA[i] | |
| } | |
| } | |
| return a >b ?1:-1; | |
| }) | |
| return res.join(''); | |
| }; | |
| ------------------------------------------------ | |
| //option obj init, more quick | |
| /** | |
| * @param {string[]} votes | |
| * @return {string} | |
| */ | |
| var rankTeams = function(votes) { | |
| if(votes.length ===1 ) { | |
| return votes[0]; | |
| } | |
| const teams = votes[0].length; | |
| const obj = {}; | |
| for(let i=0; i<votes[0].length; i++) { | |
| obj[votes[0][i]] = new Array(votes.length).fill(0); | |
| } | |
| for(let i=0; i< votes.length; i++) { | |
| for(let j=0; j<teams; j++) { | |
| obj[votes[i][j]][j]+=1 | |
| } | |
| } | |
| //console.log("obj", obj); | |
| const res = Object.keys(obj).sort((a,b)=>{ | |
| const listA = obj[a]; | |
| const listB = obj[b]; | |
| for(let i=0; i<votes[0].length; i++) { | |
| if(listA[i] !== listB[i]) { | |
| return listB[i] -listA[i] | |
| } | |
| } | |
| return a >b ?1:-1; | |
| }) | |
| return res.join(''); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment