Bulls and Cows
https://leetcode.com/problems/bulls-and-cows/description/
You are playing the followingBulls and Cowsgame with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
For example:
Write a function to return a hint according to the secret number and friend's guess, use
A
to indicate the bulls andB
to indicate the cows. In the above example, your function should return"1A3B"
.Please note that both secret number and friend's guess may contain duplicate digits, for example:
In this case, the 1st
1
in friend's guess is a bull, the 2nd or 3rd
1
is a cow, and your function should return
"1A1B"
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
Thoughts
bulls数目好树,麻烦的是cows。cows本质是算除去bulls后的secret中包含了多少个guess中的字符。这让我想到了在滑动窗口中常用的数是否数目一致的amount map.
Code
Analysis
时间复杂度O(n), 空间O(1)
Ver.2
还可以把两个循环合并。对于先在guess中出现后在secret中出现的,相当于guess先被减到负值,然后遇到secret中对应元素再把它往正数加。加到0代表当前刚好guess和secret中该元素数目相等。加到正代表guess中欠缺。
Last updated
Was this helpful?