这个数组最多只能有一个重复,或者不重复。
我需要这个算法通过一些单元测试,并且有不同版本来失败不同的测试。
如果您发现这两个解决方案有任何问题,或者知道更快的解决方案,我会感激不尽。
哈希:
在 UInt16.MaxValue 大小的数组中,无论是否有重复值,这种方法都无法通过持续时间测试。
通过 - 空数组不包含重复项
通过 - 没有重复项的小数组
通过 - 重复项为 (Repeated) 的小型数组
通过 - 重复项为 (Repeat) 的小型数组
通过 - 没有重复项的大型数组 (Repeated)
失败 - 没有重复项的大型数组 (Duration)
通过 - 有重复项的大型数组 (Repeated)
通过 - 有重复项的大型数组 (Repeat)
失败 - 有重复项的大型数组 (Duration)
失败 - 综合
public bool ContainsRepeat(UInt16[] values, out UInt16 repeat)
{
//HASH SET//
var set = new HashSet<UInt16>();
repeat = 0;
foreach (UInt16 value in values)
{
if (!set.Add(value))
{
repeat = value;
return true;
}
}
return false;
}
对重复项进行排序并进行二分搜索:
对于大小为UInt16.MaxValue的相同数组,该方法在没有重复项时无法通过持续性测试,同时在存在重复项时也无法返回正确的重复值,即使它可以用于较小的数组。
通过 - 空数组不包含重复项
通过 - 小型无重复项数组
通过 - 重复项的小型数组(Repeated)
通过 - 重复项的小型数组(Repeat)
通过 - 没有重复项的大型数组(Repeated)
不通过 - 没有重复项的大型数组(持续时间)
通过 - 重复项的大型数组(Repeated)
不通过 - 重复项的大型数组(Repeat)
通过 - 重复项的大型数组(持续时间)
不通过 - 组合
public bool ContainsRepeat(UInt16[] values, out UInt16 repeat)
{
int findRepeatingElement(UInt16[] arr, int low, int high)
{
if (low > high)
return -1;
int mid = (low + high) / 2;
if (arr[mid] != mid + 1)
{
if (mid > 0 && arr[mid] == arr[mid - 1])
return mid;
return findRepeatingElement(arr, low, mid - 1);
}
return findRepeatingElement(arr, mid + 1, high);
}
repeat = 0;
if (values.Length <= 1)
{
return false;
}
Array.Sort(values);
int index = findRepeatingElement(values, 0, values.Length - 1);
if (index != -1)
{
repeat = values[index];
return true;
}
else
{
return false;
}
}
这是我的第一篇文章,欢迎对我在这里提出问题的格式提供建议:)