[英]Removing duplicates from a sorted array without making a new one
我正在為編碼練習而頭疼,我無法找出正確的代碼。
我需要從排序數組中刪除重復項,而不創建新數組。
基本上,我需要打開這個數組:
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;
}
基本上這個想法是沿着數組移動,保留最后一個唯一數字的索引
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.