我正试图找到一种方法来优化我的算法,使运行时间为O(n²)(Big O Notation).
输入是一个包含n个元素的数组,只有正整数和负整数.我们可以假设数组已经排序.
我必须确定:对于每个r(数组的元素),r = s + t,其中s和t也是数组的元素,并且可以是相同的(s == t),或者也是零.
我试图通过检查当前数字是正数还是负数来减少我必须检查的元素数量,但是运行时间仍然太长.问题是我使用了3个while循环,这意味着在最坏的情况下运行时间为O(n³).
这是我的代码:
public static void Checker(int[] array) {
List<Integer> testlist = new ArrayList<Integer>();
int i = 0;
while (i < array.length) {
int current = array[i];
if (attached(current, array)) {
testlist.add(current);
}
i++;
}
}
public static boolean attached(int current, int[] array) {
boolean result = false;
int i = 0;
while (i < array.length && !result) {
int number1 = array[i];
int j = 0;
while (j < …Run Code Online (Sandbox Code Playgroud) 我正在编写一个 iOS 应用程序,它将使用蓝牙低功耗 (BLE) 与设备进行通信。
当我连接的设备超出范围时,我的应用程序会收到断开连接事件。
但是当设备返回范围时,我没有收到任何连接事件。
请建议任何方法来检测设备何时回到范围内。
我有一个排序算法.我知道它可以用许多其他更简单的方式编写,但这不是我的问题.
这是算法:
sort(A : Array of N, i : N, j : N)
assert j-i+1 isTwoPotency
if A[i] > A[j] then swap A[i] and A[j]
if i+1 < j then
k:= (j ? i + 1)/4
sort(A, i, j ? 2k)
sort(A, j ? 2k + 1, j)
sort(A, i + k, j ? k)
sort(A, i, j ? 2k)
sort(A, j ? 2k + 1, j)
sort(A, i + k, j ? k)
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么算法在以下情况下正常工作 …