LeetCode 面试题 16.15. 珠玑妙算

一、题目

  珠玑妙算游戏(the game of master mind)的玩法如下。

  计算机有4个槽,每个槽放一个球,颜色可能是红色(R)、黄色(Y)、绿色(G)或蓝色(B)。例如,计算机可能有RGGB 4种(槽1为红色,槽2、3为绿色,槽4为蓝色)。作为用户,你试图猜出颜色组合。打个比方,你可能会猜YRGB。要是猜对某个槽的颜色,则算一次“猜中”;要是只猜对颜色但槽位猜错了,则算一次“伪猜中”。注意,“猜中”不能算入“伪猜中”。

  给定一种颜色组合 solution 和一个猜测 guess,编写一个方法,返回猜中和伪猜中的次数 answer,其中 answer[0] 为猜中的次数,answer[1] 为伪猜中的次数。

示例:

输入: solution=“RGBY”,guess=“GGRR”
输出: [1,1]
解释: 猜中1次,伪猜中1次。

提示:

  • len(solution) = len(guess) = 4
  • solutionguess 仅包含 "R", "G", "B", "Y" 这4种字符

  点击此处跳转题目

二、C# 题解

  数据量很小,直接统计就好了。

public class Solution {
    
    
    public int[] MasterMind(string solution, string guess) {
    
    
        int[] ans = new[] {
    
     0, 0 };
        Dictionary<char, int> dic = new Dictionary<char, int>() {
    
    
            {
    
     'R', 0 },
            {
    
     'G', 0 },
            {
    
     'B', 0 },
            {
    
     'Y', 0 }
        };
        foreach (char c in solution) {
    
     dic[c]++; }
        for (var i = 0; i < solution.Length; i++) {
    
    
            if (solution[i] == guess[i]) ans[0]++;
            if (dic[guess[i]] > 0) {
    
    
                dic[guess[i]]--;
                ans[1]++;
            }
        }
        ans[1] -= ans[0];
        return ans;
    }
}
  • 时间:116 ms,击败 83.33% 使用 C# 的用户
  • 内存:40.66 MB,击败 16.67% 使用 C# 的用户

猜你喜欢

转载自blog.csdn.net/zheliku/article/details/134200932