Mok*_*rma 3 java algorithm time-complexity treeset
我正在做一个 hackerrank 问题,要求我找出使用插入排序对数组进行排序所需的移位次数,而无需实际使用插入排序对数组进行排序,因为否则时间复杂度将是 O(n^2)!这是我的超时代码。据我所知,调用 headSet 方法 n 次应该达到 O(n logn) 左右。
static class MyComp implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o1 <= o2 ? -1: 1;
}
}
// Complete the insertionSort function below.
static int insertionSort(int[] arr) {
SortedSet<Integer> set = new TreeSet<>(new MyComp());
int count=0;
for(int i=arr.length-1; i>=0;i--){
set.add(arr[i]);
int pos = set.headSet(arr[i]).size();
// System.out.println(pos);
if(pos>0){
count=count+pos;
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
创建耳机的复杂性是O(1)
为什么?
因为耳机并不是新的。它实际上是现有集合的视图。创建一个不涉及复制原始集合,甚至不涉及查找集合中的“绑定”元素。
因此,做N几次就是O(N)。
但是,您的代码不是O(N)的原因是
set.headSet(someElement).size();
Run Code Online (Sandbox Code Playgroud)
不是O(1)。原因是size()a 的子集视图上的方法TreeSet是通过计算视图中的元素来计算的。
(AFAIK,javadoc 中没有说明这一点,但您可以通过查看TreeSet和 的源代码来推断它TreeMap。)