C# Learn from three failed test cases
Oct. 25, 2019
It is such good practice to write a solution with rich learning experience. My reading skills can not catch up since I missed three test cases.
Case study
I failed three test cases.
- [[1,2],[1,2],[1,1],[1,2],[2,2]] should be 3, not 0
- [[1,2],[1,2],[1,1],[1,2],[2,2]] should be 3, not 2
- [[1,1],[2,2],[1,1],[1,2],[1,2],[1,1]] should be 4, not 7
I learned from the first test case, and then I decided to keep the count of key. I design to use integer 10 * i + j to represent a pair with integer [i, j].
I chose to write using HashSet, since count of key has to be saved, so I just choose to use an integer array, using index value as key, value as count of key.
I chose to write using HashSet, since count of key has to be saved, so I just choose to use an integer array, using index value as key, value as count of key.
I spent over 10 minutes to write the first submission, and then 2 minutes to fix failed test case 1, and then another three minutes to fix failed test case 2, and then another two minutes to failed test case 3.
The following is my C# code passing all test cases.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1128_Number_of_dominos
{
class Program
{
static void Main(string[] args)
{
}
/// <summary>
/// Oct. 25, 2019
/// 1128. Number of Equivalent Domino Pairs
/// Failed test case:
/// 1. [[1,2],[1,2],[1,1],[1,2],[2,2]] should be 3, not 0
/// 2. [[1,2],[1,2],[1,1],[1,2],[2,2]] should be 3, not 2
/// 3. [[1,1],[2,2],[1,1],[1,2],[1,2],[1,1]] should be 4, not 7
///
/// </summary>
/// <param name="dominoes"></param>
/// <returns></returns>
public int NumEquivDominoPairs(int[][] dominoes)
{
var rows = dominoes.Length;
var keyCount = new int[100];
int count = 0;
for (int i = 0; i < rows; i++)
{
var first = dominoes[i][0];
var second = dominoes[i][1];
var reversedKey = second * 10 + first;
var key = first * 10 + second;
count += keyCount[key];
if (key != reversedKey)
{
count += keyCount[reversedKey];
}
keyCount[key]++;
}
return count;
}
}
}
No comments:
Post a Comment