2020-06-19
猜数字游戏
你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下:
题解:
思路1:哈希表
var getHint = function (secret, guess) { let hash1 = new Map(), hash2 = new Map(), bull = 0, cows = 0; for (let i = 0; i < secret.length; i++) { if (hash1.has(secret[i])) hash1.set(secret[i], hash1.get(secret[i]) + 1); else hash1.set(secret[i], 1); if (hash2.has(guess[i])) hash2.set(guess[i], hash2.get(guess[i]) + 1); else hash2.set(guess[i], 1); if (secret[i] === guess[i]) bull++; } hash1.forEach((item, key) => { if (hash2.has(key)) cows += Math.min(hash2.get(key), item); }) return bull + 'A' + (cows - bull) + 'B'; };