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();
解决方案
更新
我又试了一次,因为我有强迫症,现在是咖啡时间
正如所指出的,原件在特殊情况下不起作用
i + 1 == j && numbers[i] != numbers[j]
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));
输出
1,2,3,4,5,6,7,8,9,10,11,12,14,0,0,0,0,0,0
原来的
它很简单
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
或者一个更具可读性的解决方案,而不需要花哨
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;
}
基本上这个想法是沿着数组移动,保持最后一个唯一数字的索引
推荐阅读
- c - 如何从文件中加载 ac 字符串
- flutter - 可以更改图标相对于 Tab 中文本的位置吗?
- python - Django + Gunicorn 与 gevent 工作人员,在视图中使用 asyncio
- c - (已解决)C 2D 数组:从每一行查找最大值,从每一列查找最小值
- java - 如何用 Feign 正确调用 api?
- testing - 如何在 Raku 中创建组合范围/特征声明符?
- java - JavaFX 矩形不更新
- java - 如何在文本文件中查找词频?
- python - 有人可以解释一下循环是如何工作的吗?
- arrays - 更新在多个 arrayFilters 上创建了冲突