gpt4 book ai didi

java - 查找已排序和移位数组的最小值,时间复杂度优于 O(n)

转载 作者:行者123 更新时间:2023-11-30 01:50:18 30 4
gpt4 key购买 nike

我们有一个任务来搜索排序数组的最小元素,然后向右移动。例如:[1, 5, 6, 19, 56, 101] 变为 [19, 56, 101, 1, 5, 6]。该方法应该使用分治算法来实现,并且应该具有比 O(n) 更好的渐近时间复杂度。编辑:我忘记添加数组中的元素是唯一的。

我已经实现了一个方法,想问一下这是否比 O(n) 更好,以及是否有方法可以改进我的方法。

public class FindMinimum {
public void findMinimum(int[] arr) {

// the recursive method ends when the length of the array is smaller than 2
if (arr.length < 2) {
return;
}

int mid = arr.length / 2;

/*
* if the array length is greater or the same as two, check if the middle
* element is smaller as the element before that. And print the middle element
* if it's true.
*/
if (arr.length >= 2) {
if (arr[mid - 1] > arr[mid]) {
System.out.println("Minimum: " + arr[mid]);
return;
}
}

/*
* separate the array in two sub-arrays through the middle and start the method
* with those two arrays again.
*/
int[] leftArr = new int[mid];
int[] rightArr = new int[arr.length - mid];
for (int i = 0; i < mid; i++) {
leftArr[i] = arr[i];
}
for (int i = mid; i < arr.length; i++) {
rightArr[i - mid] = arr[i];
}
findMinimum(leftArr);
findMinimum(rightArr);
}
}

最佳答案

在 Java 中,您可以使用列表,因为您可以创建子列表。

private Integer findMinimum(List<Integer> list) {
if (list.size() < 2)
return list.get(0);

int mid = list.size() / 2;

// create left and right list
List<Integer> leftList = list.subList(0, mid);
List<Integer> rightList = list.subList(mid, list.size());

if (leftList.get(leftList.size() - 1) <= rightList.get(rightList.size() - 1))
return findMin(leftList);
else
return findMin(rightList);
}

当您使用 Java 创建子列表时,没有副本。因此创建一个新的子列表需要 O(1) 的复杂度。所以该函数的复杂度为O(logn)。

关于java - 查找已排序和移位数组的最小值,时间复杂度优于 O(n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313529/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com