【Leetcode】299-bulls-and-cows【Java实现】【hash table】
2015-11-05 17:48
393 查看
最近有空就刷一下leetcode,299题自己的方法居然要50ms+,都不好意思贴出来。在discussion中看到了一个hash的方法。学习了一下,很巧妙,加油吧!
stem:
code:
也贴一下自己的代码吧。。。虽然真的很挫。。。
这道题开始理解题意有问题,要注意,计算bull和cow的一一对应关系。
stem:
You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it. Each time your friend guesses a number, you give a hint. The hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"). Your friend will use those hints to find out the secret number. For example: Secret number: "1807" Friend's guess: "7810" Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B 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: Secret number: "1123" Friend's guess: "0111" 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.
code:
public class Solution { public String getHint(String secret, String guess) { int len=secret.length(); int A=0; int B=0; int count[]=new int[10]; for(int i=0;i<len;i++){ int s=secret.charAt(i)-'0'; int g=guess.charAt(i)-'0'; if(s==g){ A++; }else{ if(count[g]>0){ //如果g这里之前多出一个和g匹配的则B加1 B++; } if(count[s]<0){ //如果之前少一个和s匹配的,则B加1 B++; } count[g]--; //缺一个和g匹配的 count[s]++; //s这里多一个匹配的 } } return A+"A"+B+"B"; } }
也贴一下自己的代码吧。。。虽然真的很挫。。。
public class Solution { public String getHint(String secret, String guess) { int len=secret.length(); if(len==0) //do not forget special situation return "0A0B"; int A=0; int B=0; int flagA[]=new int[len]; for(int i=0;i<len;i++){ char s=secret.charAt(i); char g=guess.charAt(i); if(s==g){ A++; }else{ for(int j=0;j<len;j++){ char sj=secret.charAt(j); char gj=guess.charAt(j); if(g==sj && sj!=gj && flagA[j]!=1){ B++; flagA[j]=1; break; } } } } return A+"A"+B+"B"; } }完全没有技术含量可言。见笑。做了几道leetcode的题,发现hash是一个好方法,但感觉自己还没有抓住精髓。
这道题开始理解题意有问题,要注意,计算bull和cow的一一对应关系。
相关文章推荐
- 《Java并发编程从入门到精通》目录
- spring mvc中log4j的配置与使用
- Java抽象类与接口
- Java注解Annotation基础
- String类(二)
- Spring_Security_3.0.1中文参考文档 2 Security命名空间配置
- 关于velocity tool2.0+springMVC的配置
- JAVA_SE基础——50.接口关系下的多态
- Spring定时器配置
- java基础关于线程
- 详解java版本迭代中的 BIO、NIO和AIO
- Java语言基础之集合乱舞Step2
- 今天在给同事改程序的时候,发现了java中Runtime
- Java初学者都必须理解的六大问题
- Spring_Security_3.0.1中文参考文档 1 介绍
- 无聊,统计MyEclipse下面工程代码量
- Java微观探源(二)_一个例子看懂JVM内存分配和回收
- java 中执行顺序
- java自带线程池和队列详细讲解
- Java图形用户界面——AWT概述