简体   繁体   English

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

[英]Removing duplicates from a sorted array without making a new one

I'm breaking my head over a coding exercise and I can't figure out the correct code.我正在为编码练习而头疼,我无法找出正确的代码。

I need to remove duplicates from a sorted array, without making a new array.我需要从排序数组中删除重复项,而不创建新数组。

Basically, I need to turn this array:基本上,我需要打开这个数组:

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

into this:进入这个:

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

My code:我的代码:

//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();

Update更新

I gave this another go because i have OCD and it was coffee time我又试了一次,因为我有强迫症,现在是咖啡时间

As pointed out, the original doesn't work in the special case that正如所指出的,原始在特殊情况下不起作用

i + 1 == j && numbers[i] != numbers[j]

ps thanks to @EricLippert for the code review and actually testing it. ps 感谢@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));

Output输出

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

Full Demo Here完整演示在这里


Original原来的

Its as simple as就这么简单

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

Output输出

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

Full Demo Here完整演示在这里

Or a much more readable solution with out getting fancy或者一个更易读的解决方案,而不是花哨

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;
   
}

Basically the idea, is move along the array, keeping an index of the last unique number基本上这个想法是沿着数组移动,保留最后一个唯一数字的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM