【发布时间】:2016-02-17 15:23:13
【问题描述】:
有两个排序的连续数数组合并为一个数组。 两个数组都有不同的数字。
ex :
{1, 2, 3, 4, 5, 6, 7, 8, 9} and
{10, 11, 12, 13, 14}
int[] resultArr = {10, 11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9};
^
寻找起点索引的算法。如果我们将其视为循环数组,它将在从起点迭代时按排序顺序进行。
在上面的例子中,起始索引将是 "4"
我写了下面的示例程序来解决这个问题,但对时间复杂度不满意。
谁能告诉我以下代码的时间复杂度,并为这个问题提供更好的解决方案。
public class FindStartingPoint {
public static Integer no = null;
private static void findStartingPoint(int[] arr, int low, int mid, int high) {
if (no != null)
return;
else if (high - low <= 1)
return;
else if (arr[mid] > arr[mid + 1]) {
no = mid + 1;
return;
}
findStartingPoint(arr, low, (low + mid) / 2, mid);
findStartingPoint(arr, mid, (mid + high) / 2, high);
}
public static void main(String[] args) {
int[] arr = {12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
findStartingPoint(arr, 0, arr.length / 2, arr.length - 1);
System.out.println(no);
}
}
提前致谢。 :-)
【问题讨论】:
-
等一下,你是不是要在数组中找到最小的数字?
-
@JordanSeanor ,不,我正在尝试找出最低 no 数组的索引(这将是起点)
-
如果两个数组分别是
{1,2,3}和{4,5,6},则没有解决办法,所以仅仅排序并有不同的元素是不够的。 -
@biziclop,结果数组未排序。考虑一下,具有较大 no 的数组首先出现。在您的示例中,它将是 {4,5,6} 和 {1,2,3}。结果数组将是 {4,5,6,1,2,3},答案是“3”,它是数字“1”的索引
-
@ManosNikolaidis 不一定。如果最小的数字右边的所有数字都小于左边的所有数字,则可以分而治之。
标签: java arrays algorithm time-complexity divide-and-conquer