[英]What is the time-complexity of a program that finds the length of the longest consecutive sequence in an array of integers?
Can somebody explain to me what the time-complexity of this program is?有人可以向我解释这个程序的时间复杂度是多少吗?
public static void main(String[] args) {
int arr[] = { 1, 9, 3, 10, 4, 20, 2};
ConsecutiveSequence(arr);
}
public static void ConsecutiveSequence(int []a){
Arrays.sort(a);
int k =1;
int n = a.length;
int max_length=0;
for(int i =0;i<n-1;i++){
if(a[i]+1==a[i+1]){
k++;
if(i==n-2){
max_length=Math.max(max_length,k);
}
}else{
max_length=Math.max(max_length,k);
k=1;
}
}
System.out.println(max_length);
}
The time complexity is N log (N)
.时间复杂度为
N log (N)
。 Why?为什么?
Arrays.sort(a);
for(int i =0;i<n-1;i++){
if(a[i]+1==a[i+1]){
k++;
if(i==n-2){
max_length=Math.max(max_length,k);
}
}else{
max_length=Math.max(max_length,k);
k=1;
}
}
The operation:操作:
Arrays.sort(a);
has a well-know complexity of N log (N)
.有一个众所周知的复杂度
N log (N)
。 As one confirm here :作为一个确认这里:
This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.
该算法在许多数据集上提供 O(n log(n)) 性能,导致其他快速排序降低到二次性能,并且通常比传统的(单轴)快速排序实现更快。
For the loop you iterative n-1
times and for each iteration you performance constant operations.对于循环,您迭代
n-1
次,并且对于每次迭代,您执行恒定操作。 So (N-1) * C.所以 (N-1) * C。
So the overall complexity is N log (N) + (N - 1) * c
.所以总体复杂度为
N log (N) + (N - 1) * c
。 Since with increment of the input N log (N)
grows much faster than (N - 1), the complexity can be represented by O(N log (N)
).由于随着输入
N log (N)
的增加,其增长速度远快于 (N - 1),因此复杂度可以by O(N log (N)
) 表示。 For more information on why it can be represented by O(N log (N))
have a look at this SO Thread .有关为什么它可以用
O(N log (N))
表示的更多信息,请查看这个 SO Thread 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.