【问题标题】:How to check if int occurs in list 3 times?如何检查 int 是否在列表中出现 3 次?
【发布时间】:2020-10-13 03:45:57
【问题描述】:

我有一个包含整数的列表,所有整数都从 0 到 2。现在我必须检查这些数字中的任何一个是否恰好出现 3 次。如何检查?

例子:

{ 2, 1, 0, 0, 1, 0 } //this is true

{ 1, 1, 2, 0, 0 } //this is false

{ 0, 0, 0, 1, 1, 1, 2, 2, 2 } //this is true

【问题讨论】:

  • Java、Dart、C++(其中任何一个)实现是否正常
  • @Jasurbek 我正在使用 c#
  • 你尝试过使用 oldscool 循环吗?

标签: c# list integer


【解决方案1】:

您可以为此使用 LINQ:

bool containsNum3x = 
    list
        .GroupBy(i => i) // group the 0s into a subset, the 1s into a subset, etc
        .Any(s => s.Count()  == 3); // check if the size of any subset is exactly 3

文档:

您可能需要在代码文件顶部按顺序添加using System.Linq

【讨论】:

    【解决方案2】:

    使用可以为此使用字典。时间复杂度 O(N) 空间复杂度 O(N)

    static void countFreq(List<int> ls)
    {
        Dictionary<int, int> dict = new Dictionary<int, int>();
    
        for (int i = 0; i < ls.Count; i++)
        {
            if (dict.ContainsKey(ls[i]))
            {
                dict[ls[i]] =  dict[ls[i]]+ 1;
            }
            else
            {
                dict.Add(ls[i], 1);
            }
        }
    
                
        for (int i = 0; i < ls.Count; i++)
        {
            if (dict.ContainsKey(ls[i]) && dict[ls[i]] != -1)
            {
                Console.WriteLine(ls[i] + " " + dict[ls[i]]);
                dict[ls[i]] = -1;
            }
        }
    }
    
                
        for (int i = 0; i < ls.Count; i++)
        {
            if (dict.ContainsKey(ls[i]) && dict[ls[i]] != -1)
            {
                Console.WriteLine(ls[i] + " " + dict[ls[i]]);
                dict.Remove(ls[i]);
                dict.Add(ls[i], -1);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:
      private bool containsIntNTimes (List<int> intList, int lookFor, int amount)
      {
          foreach(int i in intList)
          {
              if(i == lookFor)
                  amount--;
      
              if (amount == 0)
                  return true;
          }
          
          return false;
      }
      
      
      containsIntNTimes(myIntList, 0, 3);
      containsIntNTimes(myIntList, 1, 3);
      containsIntNTimes(myIntList, 2, 3);
      

      【讨论】:

        猜你喜欢
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        • 1970-01-01
        • 2017-11-26
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多