【发布时间】:2014-01-31 20:13:06
【问题描述】:
我已经解决了这些问题,所以我不是在寻找直接的答案。我正在寻找有关我是否正确执行此操作的指导,如果没有,可能会解释我为什么不正确。 :)
所以我有这两个问题。我已经评论了我为什么得到我的答案的逻辑。如果有人可以请验证我这样做是否正确?
public static Integer findTripleB(int[] anArray) {
//Method Variable: n
if (anArray.length <= 2) {
return false;
} //Time Complexity: 1
// use insertion sort to sort anArray
for (int i = 1; i < anArray.length; i++) {//TC 1+(n+1)+n
// insert anArray[i]
int j = i-1; //TC 1
int element=anArray[i]; //TC 1
while (j >= 0 && anArray[j] > element) {//TC log(n)
anArray[j+1] = anArray[j]; //TC 1
j--; //TC 1
}
anArray[j+1] = element; //TC 1
} //Total TC: (2n+2)(1+1+log(n)(2)) = (2n+2)(2+2log(n)) = 4n+(2log(n))(2n)+4+4log(n)
// check whether anArray contains three consecutive
// elements of the same value
for (int i = 0; i < anArray.length-2; i++) {//TC 1+n-1+n
if (anArray[i] == anArray[i+2]) {//TC 1
return new Integer(anArray[i]);//TC 1
}
}//Total TC: (2n)(2) = 4n
return null;//TC 1
} //TOTAL TIME COMPLEXITY: 5+8n+4nlog(n)+4log(n)
对于最佳情况时间复杂度,我得到 O(1),因为如果数组 >= 长度 2,它将返回。在最坏的情况下,我想出了 O(n*log(n))。
对于一个更简单的问题,
boolean findTripleA(int[] anArray) { //Method Variable: n
if (anArray.length <= 2) {
return false;//TC 1
}//TC 1
for (int i=0; i < anArray.length; i++) {//TC 1+n+1+n
// check if anArray[i] occurs at least three times
// by counting how often it occurs in anArray
int count = 0;//TC 1
for (int j = 0; j < anArray.length; j++) {//TC 1+n+1+n
if (anArray[i] == anArray[j]) {
count++;
}//TC 1
}//Total TC: 2n+2
if (count >= 3) {
return true;
}//TC 1
}//Total TC: (2n+2)(1+2n+2+1) = (2n+2)(2n+4) = 4n2+12n+8
return false;//TC 1
}//TOTAL TIME COMPLEXITY: 4n2+12n+9
对于最好的情况,与第一个问题相同,O(1)。对于最坏的情况,O(n^2)。
这些是否正确,如果不正确,为什么不呢?同样,我不是在寻找答案。我正在寻求指导,因为我的教授似乎不想提供帮助,而班上的其他人也很困惑。
【问题讨论】:
标签: java math time complexity-theory