【发布时间】:2018-03-29 06:31:34
【问题描述】:
我正在尝试编写一个程序,将数组的所有不同元素放在同一个数组的左侧,然后以任何顺序将所有其他(非不同)元素放在后面。时间复杂度必须是 O(n log n),即使用排序并且不必创建额外的数组。我尝试使用以下代码打印不同的元素:
using System;
using System.Diagnostics;
public class Program
{
public static void Main()
{
int []arr = {1, 1, 6, 5, 4, 3, 4, 6, 1, 7, 2, 1, 4, 9};
allDistinct(arr);
}
public static void allDistinct(int[] x)
{
int n = x.Length;
Trace.Assert(n>0);
Array.Sort(x); //O(n log n)
for (int i = 0; i < n; i++)
{
// Move the index ahead while
// there are duplicates
while (i < n - 1 && x[i] == x[i + 1])
i++;
}
Console.WriteLine(x[i]);
}
}
但是,我希望我的函数具有以下形式
public static int[] allDistinct(int[] x)
然后在Main()中使用辅助函数打印数组
printArray(allDistinct(arr));
在哪里
public static void printArray(int[] array)
{
for(int i=0; i<array.Length; ++i)
{
Console.Write("" + array[i] + " ");
}
Console.WriteLine("");
}
我尝试使用交换函数,但没有成功得到我想要的,即给定数组
1 1 6 5 4 3 4 6 1 7 2 1 4 9
我的输出应该是
1 2 3 4 5 6 7 9 + (duble elements in whatever order, e.g. 1 1 1 4 4 6)
感谢您的建议
【问题讨论】:
-
也许
List<int>对你想做的事情会更容易 -
提示:对数组进行排序,然后执行两次循环,第一次扫描它输出每个不同的值(即,每当它发生变化时),第二个输出非不同的值(即,在变化之后)输出每个相同的值)。使用
IEnumerable和yield return可以更轻松地编写代码。如果您必须完全“就地”完成,请考虑在每一端开始两个指针,左侧接受唯一值,右侧累积额外的非唯一值。 -
请说明左侧部分是否必须进行排序(因为答案表明每个人都不清楚)