LeetCode Note Java 00299:Bulls and Cows
情境題:猜數字,輸入答案跟猜的數字,回傳幾 A (數字對位置也對) 幾 B (數字對位置錯)。
題目
Bulls and Cows Medium
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The number of “bulls”, which are digits in the guess that are in the correct position.
The number of “cows”, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend’s guess guess, return the hint for your friend’s guess.
The hint should be formatted as “xAyB”, where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
解法
1 | class Solution { |
檢討
在比較序列時,這種共用 map 或 array 來相反計數 (一加一減) 的方式滿常見的,但有時候我邏輯會跟不上,只能多做題目強迫做這種思考了。
參考資料
One pass Java solution