Array remove duplicate elements

前端 未结 12 1562
陌清茗
陌清茗 2020-11-27 16:17

I have an unsorted array, what is the best method to remove all the duplicates of an element if present?

e.g:

a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3]
         


        
12条回答
  •  没有蜡笔的小新
    2020-11-27 16:41

    If you don't need to keep the original object you can loop it and create a new array of unique values. In C# use a List to get access to the required functionality. It's not the most attractive or intelligent solution, but it works.

    int[] numbers = new int[] {1,2,3,4,5,1,2,2,2,3,4,5,5,5,5,4,3,2,3,4,5};
    List unique = new List();
    
    foreach (int i in numbers)
         if (!unique.Contains(i))
              unique.Add(i);
    
    unique.Sort();
    numbers = unique.ToArray();
    

提交回复
热议问题