下面我需要一些帮助,我为一个赋值创建了一些代码。我很难弄清楚这个算法的时间复杂性。我看了一下,相信O表示法是0(n(,函数是F(n)= 4 + 2n
。但我认为这是不正确的。
/**
*mostOften method
*@param receives Array[] , int
*/
static int mostOften(int array[] , int n){
//Array to be sorted in ascending order
Arrays.sort(array);
//counts number of max occurrences in the array
int maxO = 1;
//Keeps track of the integer at Array[i].
int result = array[0];
//variable to count occurrences
int count = 1;
/**
*loop passes through array in linear motion and compares index at i and index at
* i - 1. For every possible outcome count and maxO are incremented accordingly.
*/
for(int i = 1 ; i < n ; i++){
//If integers are the same increment count.
if (array[i] == array[i - 1]){
count++;
}//close if statement
// else if integers are not the same
else{
//if count is larger thatn maxO that integer is the highers occurrence
if (count > maxO){
//count is now maxO
maxO = count;
//replaces result with integers with highest occurrence.
result = array[i - 1];
}//close if statement
//reset count to 1.
count = 1;
}//close else statement
}//close for loop
//@returns int data type
return result;
}//close mostOften method
我只是想指出Arrays.sort本身就是O(n-logn(。如果我们忽略这一点,循环将花费线性时间。