簡體   English   中英

從數組中刪除重復項並創建一個新數組

[英]Remove duplicates from array and create a new array

我想刪除此數組中的所有重復項,但不能完全使其正常工作。 當所有重復項都被刪除后,我想創建一個沒有刪除數字的新數組。 這是我的代碼:

  static void Main(string[] args)
    {
        int[] s = { 11, 11, 12, 12, 13, 13, 14, 15, 16 };
        int[] q = s.Distinct().ToArray();

        Console.WriteLine(q.ToString());
        Console.ReadLine();
    }

這將打印數組{11,12,13,13,14,15,16}; 但我希望它打印數組{14,15,16}。

采用:

int[] s = { 11, 11, 12, 12, 13, 13, 14, 15, 16 };
var NotDuplicateItems = s.GroupBy(r => r)
    .Where(grp => grp.Count() == 1)
    .Select(r => r.Key)
    .ToArray();

以上將為您提供在數組s中不重復的項目

Distinct返回一個集合,其中刪除了所有重復項。 但是,它不會刪除原始項目(以后重復的項目)。

要刪除所有重復的項,即“計數”大於1的項:

int[] q = s.Where(i => s.Count(j => j == i) == 1).ToArray();

這是O(n ^ 2),所以不要在大型​​集合上這樣做。

如果您知道要對輸入數組進行排序(在您的示例中),則應該利用它。 如果這樣做,則可以遍歷一次數組:

public int[] RemoveDuplicates(int[] source)
{
    bool occurredOnce = true;
    int currentItem = source[0];

    var result = new List<int>();

    for (int i = 1; i < source.Length; i++)
    {
        if (source[i] != currentItem)
        {
            if (occurredOnce)
            {
                result.Add(currentItem);
            }

            currentItem = source[i];
            occurredOnce = true;
        }
        else 
        {
            occurredOnce = false;
        }
    }

    if (occurredOnce)
    {
        result.Add(currentItem);
    }

    return result.ToArray();
}

示例: https //dotnetfiddle.net/4qgEFs

我目前無法編碼..但是這是我的思考過程....

取第一個數字,然后將其從字符串(或數組)的其余部分中刪除。

然后搜索剛剛從字符串(或數組)中刪除的數字。

如果再次找到它,它將不會打印該號碼。 如果不是,則顯示數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM