【问题标题】:Comparing 2 queues and finding an element that does not exist in both queues比较 2 个队列并找到两个队列中都不存在的元素
【发布时间】:2015-10-11 08:38:33
【问题描述】:

我目前正在尝试比较 2 个队列。队列中的大多数条目将是重复的(两个队列将具有相同的条目)。我想要做的是,找到两个队列中都不存在的条目。

例如,假设以下是有问题的 2 个队列。

1st queue - A S D F G
2nd queue - S A D G Q

条目 A、S、D、G 都存在于两个队列中。但是,条目 F 对于第一个队列是唯一的,而 Q 对于第二个队列是唯一的。我希望能够找出哪些条目是唯一的。有没有这样的功能?

为了这个问题,我需要使用队列,因为 FIFO 行为至关重要。

【问题讨论】:

标签: c# queue


【解决方案1】:
var firstQueue = new  Queue<char>() {};
var secondQueue = new Queue<char>() {};

foreach (char obj in firstQueue)
{
    if (!secondQueue.Contains(obj))
    {
        // Doesn't exist in the second queue -> Do something
    }
}

一种更短的方法是使用 LINQ:

// Will contain all the values that secondQueue doesn't contain.
var exampleOne = firstQueue.Except(secondQueue);

// Will contain all the values that firstQueue doesn't contain.
var exampleTwo = secondQueue.Except(firstQueue);

// Will contain all the values that both queues have in common.
var exampleThree = firstQueue.Intersect(secondQueue);

【讨论】:

    【解决方案2】:

    将打印与控制台窗口不匹配的元素。您也可以将它们保存到列表或数组中。

    using System;
    using System.Collections;
    using System.Collections.Generic;
    
    
    public class QueueDemo
    {
        public static void Main(String[] args)
        {
            List<char> list1 = new List<char>{'A', 'S', 'D', 'F', 'G' };
            Queue<char> Q1 = new Queue<char>(list1);
    
            List<char> list2 = new List<char>{'S', 'A', 'D', 'G', 'Q' };
            Queue<char> Q2 = new Queue<char>(list2);
    
            foreach (char e in Q1)
            {
                if (!Q2.Contains(e))
                {
                    Console.WriteLine(e);
                }
            }
    
            foreach (char e in Q2)
            {
                if (!Q1.Contains(e))
                {
                    Console.WriteLine(e);
                }
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2019-12-07
      相关资源
      最近更新 更多