从排序数组中删除重复项而无需创建新数组

时间:2019-01-11 23:44:31

标签: c#

我在进行编码练习时不知所措,我找不到正确的代码。

我需要从已排序的数组中删除重复项,而无需创建新数组。

基本上,我需要打开这个数组:

1 1 2 2 3 3 4 4 5 5 6 6 6 7 7

对此:

1 2 3 4 5 6 7 0 0 0 0 0 0 0 0

我的代码:

//show original array
        int[] numbers = new int[] {1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7};


        for (int counter = 0; counter < 15; counter++)
        {
            Console.Write(numbers[counter] + " ");
        }
        Console.WriteLine();

//remove the duplicates

       for (int counter = 0; counter  < (15 - 1); counter++)
        {
           ???

        }


//show updated array
        for (int counter = 0; counter < 15; counter++)
        {
            Console.Write(numbers[counter] + " ");
        }

        Console.ReadLine();

1 个答案:

答案 0 :(得分:0)

更新

我又去了一次,因为我有强迫症,现在是喝咖啡的时间

如前所述,在特殊情况下

不能使用原始格式
i + 1 == j && numbers[i] != numbers[j]

p.s感谢@EricLippert进行代码审查和实际测试。

int[] numbers = new int[] { 1, 2, 3, 4, 5, 5, 6, 6, 6, 7, 8, 9, 10, 10, 11, 12, 12, 14, 14 };

// i = unique = 0
// j = array index = 1
for (int i = 0, j = 1; j < numbers.Length; j++)
{
   // if i and j are different we can move our unique index
   if (numbers[i] != numbers[j])
      if (++i == j) // special case, lets move on ++i
         continue; // note we don't want to zero out numbers[j], so just continue
      else
         numbers[i] = numbers[j];

   // wipe the guff
   numbers[j] = 0;
}

Console.WriteLine(string.Join(",", numbers));

输出

1,2,3,4,5,6,7,8,9,10,11,12,14,0,0,0,0,0,0

Full Demo Here


原始

就像

一样简单
for (int i = 0, j = 1; j < numbers.Length; numbers[j++] = 0)        
   if(numbers[i] != numbers[j])
      numbers[++i] = numbers[j];

输出

1,2,3,4,5,6,7,0,0,0,0,0,0,0,0

Full Demo Here

或者一个没有花哨的可读性更强的解决方案

for (int i = 0, j = 1; j < numbers.Length;j++ )
{
   // is the last unique different from the current array index
   if (numbers[i] != numbers[j])
   {
      // increment the last unique, so we don't overwrite it
      i++; 
      // add the unique number at the next logical place
      numbers[i] = numbers[j];
   }

   // wipe the guff
   numbers[j] = 0;

}

基本上,这个想法是沿着数组移动,并保留最后一个唯一数字的索引