gpt4 book ai didi

c# - 从 C# 中的给定整数数组中获取第 k 个公共(public)元素

转载 作者:太空狗 更新时间:2023-10-30 00:30:03 25 4
gpt4 key购买 nike

我想从数组中找出第 k 个最常见的元素,我能够找到最常见的元素,但我不知道如何找到第 k 个常见的元素。

我试过:

 private static int KthCommonElement(int[] a, int k)
{
var counts = new Dictionary<int, int>();
foreach (int number in a)
{
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts)
{
if (pair.Value > occurrences)
{
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);

return mostCommonNumber;
}

最佳答案

您可以按元素的出现对元素进行排序,然后取第 k 个元素:

int[] orderedByOccurence = a.OrderByDescending(i => counts[i]).ToArray();
if (orderedByOccurence.Length > k)
Console.WriteLine($"{k}th most common element: {orderedByOccurence[k]});

但正如 Adam 在评论中指出的那样,您可以使用 GroupBy 来缩短代码:

private static int KthCommonElement(int[] a, int k)
{
if (a == null) throw new ArgumentNullException(nameof(a));
if (a.Length == 0) throw new ArgumentException();
if (k < 0) throw new ArgumentOutOfRangeException();

var ordered = a.GroupBy(i => i, (i, o) => new { Value = i, Occurences = o.Count()})
.OrderByDescending(g => g.Occurences)
.ToArray();

int index = k;
if (ordered.Length <= index)
{
// there are less than k distinct values in the source array
// so add error handling here, either throw an exception or
// return a "magic value" that indicates an error or return the last element
index = ordered.Length - 1;
}

var result = ordered[index];
Console.WriteLine("The most common number is {0} and it appears {1} times",
result.Value, result.Occurrences);

return result.Value;
}

关于c# - 从 C# 中的给定整数数组中获取第 k 个公共(public)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42482285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com