HT299BullsAndCows

来源:互联网 发布:java 生成汉字五笔码 编辑:程序博客网 时间:2024/06/06 00:57

Method1

  • Use two arrays, calculate the bulls and cows separately.

Method2

  • HashMap: Use of hashmap can identify bulls quickly, but for cows, we have to eliminate existing bulls from both strings, which is a problem.
  • 做了半天才想起来hashset不可duplicate, 因此并不适用于重复数字
  • 于是用了LinkedList和HashMap, 一下是当时写的思路
     * Put secret in HashMap, and guess in LinkedLIst     * Find the bulls and delete them in both HashMap and HashSet     * Cannot use same method fow cows, because cannot remove element in hashMap by values. Must by keys

后来发现, 一旦删除linkedlist的元素, index就跟着变,再有index作为key就不对了.因此, 对于HashMap来讲,一旦用别人的index相关作为key或者value,都要注意index不可随意增减!

  • 最后才想起来怎么不用两个HashMap呢? 分分钟写完…
  • One Failed Case:
    • ”1234” and “0111” Pay attention that when you find cows, break the second loop, or it will return 0A3B instead of 0A1B

Method 3

  • Other’s solution: To get the cows, use ascii array to calculate the frequency of each number.

Method 4

  • Use the HashMap to accumulate frequency
  • One optimization of the above
    • cows = all - bulls
  • My post https://discuss.leetcode.com/topic/67559/b-all-a-hashmap-one-pass-java-solution-with-explanation
0 0
原创粉丝点击