C# 如何在整数数组中查找三元组

C# 如何在整数数组中查找三元组,c#,C#,我有一个整数数组。我想找出给定数组中是否存在任何三元组 int[] arr = [1,2,2,3,2,4]; public int FindTriplet(int[] arrayrecieve) { // TO return 1 ; // if the array has a triplet (foe example above array has 2,2,2) } 否则 返回0 }您可以使用Linq的GroupBy()查找计数至少为3的所有组: int[] arr = {1, 2, 2,

我有一个整数数组。我想找出给定数组中是否存在任何三元组

int[] arr = [1,2,2,3,2,4];

public int FindTriplet(int[] arrayrecieve)
{
// TO return 1 ; // if the array has a triplet (foe example above array has 2,2,2)
}

否则

返回0


}

您可以使用Linq的
GroupBy()
查找计数至少为3的所有组:

int[] arr = {1, 2, 2, 3, 2, 4, 1, 4, 6, 5, 4, 9};
var triplets = arr.GroupBy(x => x).Where(y => y.Count() >= 3).Select(z => z.First());
Console.WriteLine(string.Join(", ", triplets)); // Prints 2, 4
这项工作如下:

  • GroupBy(x=>x)
    将数组中的所有元素细分为相同编号的组(即所有1在一个组中,所有2在另一个组中,依此类推)
  • 其中(y=>y.Count()>=3)
    过滤组,以便只包括计数(即项目数)至少为3的组
  • Select(z=>z.First())
    选取每个过滤后的组,并仅选择每个组的第一个元素(请注意,组中的每个元素当然是相同的)
  • 请注意,您也可以编写上述三元组的初始化,如下所示:

    var triplets = 
        from number in arr
        group number by number into grouped
        where grouped.Count() >= 3
        select grouped.First();
    
    对于希望在至少有一个三元组时返回1的特定要求,您可以这样做:

    int result = triplets.Any() ? 1 : 0;
    
    (虽然我原以为您希望返回布尔而不是int)


    另外,如果您想查找计数正好为3的组,只需将
    Where()
    更改为:
    。Where(y=>y.count()==3)
    您可以使用Linq的
    GroupBy()
    查找计数至少为3的所有组:

    int[] arr = {1, 2, 2, 3, 2, 4, 1, 4, 6, 5, 4, 9};
    var triplets = arr.GroupBy(x => x).Where(y => y.Count() >= 3).Select(z => z.First());
    Console.WriteLine(string.Join(", ", triplets)); // Prints 2, 4
    
    这项工作如下:

  • GroupBy(x=>x)
    将数组中的所有元素细分为相同编号的组(即所有1在一个组中,所有2在另一个组中,依此类推)
  • 其中(y=>y.Count()>=3)
    过滤组,以便只包括计数(即项目数)至少为3的组
  • Select(z=>z.First())
    选取每个过滤后的组,并仅选择每个组的第一个元素(请注意,组中的每个元素当然是相同的)
  • 请注意,您也可以编写上述三元组的初始化,如下所示:

    var triplets = 
        from number in arr
        group number by number into grouped
        where grouped.Count() >= 3
        select grouped.First();
    
    对于希望在至少有一个三元组时返回1的特定要求,您可以这样做:

    int result = triplets.Any() ? 1 : 0;
    
    (虽然我原以为您希望返回布尔而不是int)


    另外,如果您想查找计数正好为3的组,只需将
    Where()
    更改为:
    。Where(y=>y.count()==3)
    如果您返回1或0,则可能只需返回bool,除非您有特定的理由需要int

    using System.Linq;
    using System.Collections.Generic;
    public bool hasTriplet(int[] values)
    {
        foreach (int i in values)
        {
            if (values.Where(v => v == i).ToList().Count >= 3)
            {
                return true;
            }
        }
        return false;
    }
    

    如果您要返回1或0,您可能应该只返回bool,除非您有特定的理由需要int

    using System.Linq;
    using System.Collections.Generic;
    public bool hasTriplet(int[] values)
    {
        foreach (int i in values)
        {
            if (values.Where(v => v == i).ToList().Count >= 3)
            {
                return true;
            }
        }
        return false;
    }
    

    3个嵌套循环?你试过什么吗?3个嵌套循环?你试过什么吗?