Finding swapped elements in less than O(n) time?

时间:2018-01-11 08:36:06

标签: algorithm sorting

Given a sorted array, and two elements one from left half and other from the right are swapped.Find the swapped elements.

The answer is obvious in O(n), but I want to know is it possible in O(log n)?

3 个答案:

答案 0 :(得分:3)

由于可以保证交换的元素形成不同的数组(“从左半部分到右边部分”):

  1. 首先,我们可以简单地遍历数组的前半部分,在O(n/2) = O(n)

  2. 中寻找交换元素
  3. 然后我们可以使用这个交换元素在O(log n/2) = O(log n)

  4. 中的数组的后半部分进行二进制搜索

    所以,它仍然是O(n) + O(log n) = O(n),但实际上它可能比天真的方法快一点。

答案 1 :(得分:0)

如果不完全扫描左半部分或右半部分,这是不可能的。所有未刷新的元素都与排序数组中的相同,因此它们无法为您提供搜索交换元素的线索,这是O(logN)二进制搜索等基础。

所以没有比O(N)更好的东西了。

答案 2 :(得分:0)

如果交换的元素是镜像的(即左手的第三个 - 从右手开始的第三个 - 结束),那么你可以这样做:

  1. 分成两半并扫描左半边找到异常值
  2. 通过减去来计算右侧离群值的索引 int rightOutlierIdx = arr.length - 1 - firstOutlierIdx
  3. arr[rightOutlierIdx]
  4. 获取第二个异常值

    应该更快

相关问题