# leetcode解題:(Medium) 299. Bulls and Cows 題目:[https://leetcode.com/problems/bulls-and-cows/](https://leetcode.com/problems/bulls-and-cows/) 描述:[1A2B猜數字遊戲](https://zh.wikipedia.org/zh-tw/1A2B),輸入會有猜的數字`guess`與解答數字`secret`,回傳猜的數字是幾A幾B 解題思路:猜測的數字會分為A(bull)跟B(Cow)2種,A的計算方法就是直接計算相同位置出現相同數字的次數,B的計算方法則先分別計算2個數字中除A以外出現的各個數字出現的頻率,再逐個比較猜測的數字與答案的出現頻率計算 程式碼: ```JAVA= class Solution { public String getHint(String secret, String guess) { int[] secretHash = new int[10]; int[] guessHash = new int[10]; int bulls = 0; int cows = 0; for(int i = 0; i < secret.length(); i++) { if(secret.charAt(i) == guess.charAt(i)) bulls++; else { secretHash[secret.charAt(i)-'0']++; guessHash[guess.charAt(i)-'0']++; } } for(int i = 0; i < 10; i++) { if(guessHash[i] > secretHash[i]) cows += secretHash[i]; else cows += guessHash[i]; } return new StringBuilder("").append(bulls).append("A").append(cows).append("B").toString(); } } ``` 時間複雜度:O(n) 空間複雜度:O(1) ###### tags: `leetcode` `medium` `map/set`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up