HackerRank「Count Triplets」算法题部分测试用例未通过求助
HackerRank「Count Triplets」问题排查求助
我在解决HackerRank的「Count Triplets」问题时,遇到测试用例不通过的情况:当ratio不等于1时,测试用例6和10失败。其中测试用例6包含100000个整数,我的输出结果为13621903916,但预期结果是2325652489,两者差值约110亿。不过当ratio等于1时,代码逻辑是正确的。
我的C#实现代码如下:
private static long GetNumberOfTriplets(IEnumerable<long> array, long ratio) { var frequencyByInteger = array .GroupBy(item => item) .ToDictionary(g => g.Key, g => g.LongCount()); /* If ratio is 1, then all the items in the triplet are equal. * This formula can be derived from n(n+1)/2 via induction. * But you don't need to understand this in order to help me, * as the failing test cases are using ratio != 1. */ if (ratio == 1) return frequencyByInteger.Values.Sum(v => v * (v - 1) * (v - 2) / 6); /* Looping through each distinct number, then checking if the * dictionary has the other 2 numbers necessary to form a triplet. * The frequencies of the three numbers are then * multiplied with each other in order to handle all * combinations in the case of repeated numbers. * E.g. in the array {1, 1, 3, 3, 9, 9} * there are 2*2*2=8 combinations of (1, 3, 9). */ return frequencyByInteger.Keys .Where(v => frequencyByInteger.ContainsKey(v * ratio) && frequencyByInteger.ContainsKey(v * ratio * ratio)) .Sum(v => frequencyByInteger[v] * frequencyByInteger[v * ratio] * frequencyByInteger[v * ratio * ratio]); }
我的思路是:统计每个数字的出现频率,遍历每个不同的数字,检查是否存在v*ratio和v*ratio*ratio这两个数字,若存在则将三者的频率相乘,累加所有符合条件的结果。但显然这个逻辑在某些测试用例下有问题,恳请帮忙排查代码错误。
内容的提问来源于stack exchange,提问作者starshinata
相关产品推荐
相关产品推荐

