java - 任务是在 O(n log n) 中创建一个代码,我写的这段代码的时间复杂度是多少?
问题描述
我正在学习大 O 和时间复杂度,我发现很难理解。你能帮我理解我写的这段代码的时间复杂度吗?
基本上,任务是遍历一个数字数组并计算满足的对数arr[i] > arr[j]
。就像这段代码中给出的数组一样,arr = {7, 3, 8, 1, 5}
找到的对应该是(7, 3),(7, 1),(7, 5),(3, 1),(8, 1),(8, 5)
,对的总数是6
。
任务是创建时间复杂度为 O(n log n) 的代码,但大 O 仍然让我感到困惑。我不确定这是否是 O(n^2) 并且不确定程序是否会因更大的数组而变慢。
public class Test {
public static void main(String[] args) {
int[] arr = {7, 3, 8, 1, 5};
System.out.println();
System.out.println("The number of pairs is " + countPair(arr));
}
public static int countPair(int[] arr) {
int i = 0, j = 1;
int ctr = 0;
int len = arr.length;
while (i < len) {
if (j == len) {
i++;
j = 1;
}
else if (i < j && (arr[i] > arr[j])) {
ctr++; // Counting pairs
}
j++;
}
return ctr;
}
}
输出:
The number of pairs is 6
解决方案
推荐阅读
- python - 为什么这些循环输出不同?
- javascript - 如何在 p5.js 中为 loadimage() 使用本地服务器?
- c# - 如何避免在多个地方使用 BuildServiceProvider 方法?
- python-3.x - 谷歌表格日期到熊猫日期时间意外偏移
- python - 计算一个值的实例并忽略 Pandas 中的连续重复
- python - 设置背景颜色时文本周围的白色突出显示
- angular - 茉莉花间谍 window.innerwidth 没有被调用
- node.js - NodeJS:为什么将 Date 设置为类型时会有两个小时的差异?
- python - 有没有一种方法可以在 python 中使用多处理从 kafka 主题中读取大量消息?
- javascript - React App - 我的警报窗口显示了两次