leetcode 299. Bulls and Cows | 299. 猜数字游戏(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 299. Bulls and Cows | 299. 猜数字游戏(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/bulls-and-cows/
題解
一個踩比贊多的題,給我的感覺是中規中矩沒啥特點,不知道在考察什么。。
思路是,用數組維護一個 map,用來記錄有哪些數字是出現過的,以及記錄出現次數。
如果是出現過的、且當前位置不對的話,就消耗一個出現次數。
class Solution {public String getHint(String secret, String guess) {char[] a = secret.toCharArray();char[] b = guess.toCharArray();int[] map = new int[10];int A = 0;int B = 0;for (int i = 0; i < a.length; i++) {if (a[i] == b[i]) A++;else map[a[i] - '0']++;}for (int i = 0; i < b.length; i++) {if (b[i] != a[i] && map[b[i] - '0'] > 0) {B++;map[b[i] - '0']--;}}return A + "A" + B + "B";} }總結
以上是生活随笔為你收集整理的leetcode 299. Bulls and Cows | 299. 猜数字游戏(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 289. Game o
- 下一篇: leetcode 566. Reshap