删除链表中重复项

Problem

Remove duplicates in a list

Solution

Sort the list.
Loop through the list. If the elements is not equal to last elements, that means a new element
using System;
using System.Collections.Generic;

namespace RemoveDuplicateInList
{
    class Program
    {
        static void RemoveDuplicates(List<int> list)
        {
            if(list.Count <= 1){
                return ;
            }

            list.Sort();

            int tail = 0;

            for (int i = 1; i < list.Count; ++i)
            {
                if (list[i] != list[tail])
                {
                    list[++tail] = list[i];           
                }
             }

            tail++;
            list.RemoveRange(tail, list.Count - tail);
        }

        static void Main(string[] args)
        {
            
            List<int> list = new List<int>();

            Random random = new Random(100);

            for (int i = 0; i < 41; i++)
            {
                list.Add(random.Next(0, 50));
            }

            Console.WriteLine("Before removing duplicate ");
            foreach (int k in list)
            {
                Console.Write(" {0} ", k);
            }

            Program.RemoveDuplicates(list);

            Console.WriteLine("\nAfter removing duplicates");
            foreach (int k in list)
            {
                Console.Write(" {0} ", k);
            }
            Console.WriteLine();
        }
    }
}

Output

Before removing duplicate
 48  7  33  45  17  47  35  30  17  7  48  26  18  24  48  24  44  49  19  1  5  19  44  48  25  42  45  32  8  30  5  39  25  24  28  4  43  26  23  36  13 
After removing duplicates
 1  4  5  7  8  13  17  18  19  23  24  25  26  28  30  32  33  35  36  39  42  43  44  45  47  48  49
Press any key to continue . . .



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值