LeetCode 299 Bulls and Cows
你正和你的朋友一起玩下面的公牛和母牛遊戲:你寫下一個數字然後讓你的朋友猜猜這個數字是多少. 每當你的朋友猜測時, 你提供一個提示, 表明所述猜測中有多少位數與你的密碼完全匹配,包括數字和位置(稱為”公牛”)以及有多少位數與密碼匹配但位於錯誤的位置(稱為”奶牛”)。
編寫一個函式, 根據祕密數字和朋友的猜測返回提示, 用於 A 表示公牛, B 表示奶牛.
解法
剛開始我的想法是依次獲取公牛和奶牛的數量, 但奶牛的判斷需要 O(n^2) 的時間複雜度, 後面想到, 用所有匹配的數量 - 公牛的數量就是奶牛的數量, 只需要 O(n) 的時間複雜度和 O(1) 的空間複雜度.
public String getHint(String secret, String guess) { int[] table = new int[10]; int total = 0; int bulls = 0; for (char c :secret.toCharArray()) { table[c - '0']++; } for (int i = 0; i < guess.length(); i++) { if (secret.charAt(i) == guess.charAt(i)) { bulls++; } if (table[guess.charAt(i) - '0']-- > 0) { total++; } } return bulls + "A" + (total - bulls)+ "B"; }
Runtime: 1 ms, faster than 100.00% of Java online submissions for Bulls and Cows.