每日打卡

2021-11-08 299- 猜数字游戏

2021-11-08  本文已影响0人  16孙一凡通工

两种思路 hashmap和数组遍历

第一种思路 hashmap实现,hashmap键值储存secret的值,value储存secret的值在数组当中出现的个数。将题目转化成判断同一个地方是否相同,接着进行hashmap判断,遍历guess数组,判定hashmap是否包含guess数组的值,若包含则统计值加1,并且hashmap对应的值减一

class Solution {
    public String getHint(String secret, String guess) {
        HashMap<String,Integer> hashMap=new HashMap<>();
        int n=secret.length();
        int[] arr=new int[n];
        int count_A=0,count_B=0;
        int tmp_value=0;
        String tmp;

        for(int i=0;i<n;i++){
            tmp=(secret.substring(i,i+1));
               
            if (hashMap.containsKey(tmp)){
                tmp_value=hashMap.get(tmp);
                tmp_value++;
                hashMap.replace(tmp,tmp_value);
            }else{
                hashMap.put(tmp,1);
            }
            
        
            if (Integer.parseInt(tmp)==Integer.parseInt(guess.substring(i,i+1))){
               

                count_A++;
                 tmp_value=hashMap.get(tmp);
                 tmp_value--;
                hashMap.replace(tmp,tmp_value);
                guess=guess.replaceFirst(guess.substring(i,i+1), "A");
            }
        
        }
        
          for(int i=0;i<n;i++){

                tmp=(guess.substring(i,i+1));

              if (hashMap.containsKey(tmp) && hashMap.get(tmp)!=0){
                   System.out.println(hashMap.get(tmp));
                  count_B++;
                    tmp_value=hashMap.get(tmp);
                    tmp_value--;
                   hashMap.replace(tmp,tmp_value);

              }

          }
          String res=Integer.toString(count_A)+"A"+Integer.toString(count_B)+"B";
          return res;
    }
}

看了解析之后,发现想麻烦了,其实可以直接用数组实现,针对相同地方的值直接比较,不同地方的值,声明两个数组,数组存储键值key是secret和guess数组的值,value是出现个数,只需要统计两个数组相同键值的最小值即可,妙啊。

import "strconv"
func getHint(secret string, guess string) string {


   count_A:=0;count_B:=0;
   var arr_A [10]int;
   var  arr_B [10]int;

    for i:=0;i<len(secret);i++{
        if secret[i]==guess[i]{
            count_A++;
        }else{
            arr_A[secret[i]-'0']++;
             arr_B[guess[i]-'0']++;
        }
    }
    for i:=0;i<len(arr_A);i++{
        count_B+=min(arr_A[i],arr_B[i]);

    }
    return strconv.Itoa(count_A)+"A"+strconv.Itoa(count_B)+"B";
}
func min(num1 int,num2 int)int{

    if num1>num2{
        return num2;
    }
    return num1;
}
上一篇 下一篇

猜你喜欢

热点阅读