下面的代碼是查找一個數字在數組中顯示的次數。 例如:給定代碼的時間複雜度。
1,2,2,2,3,4,5,5,5,5 number 2 = 3 times number 5 = 4 times.
什麼是下面的代碼Java中的時間複雜度? 解決時間複雜性問題的最佳方法是什麼?
public static void main(String[]args)
{
int[] data = {1,1,2,3,4,4,4,5,6,7,8,8,8,8};
System.out.println(count(data,8));
}
public static int count(int[] a, int x)
{
int count=0;
int index=0;
while(index<a.length)
{
if(a[index]==x)
{
count++;
}
index++;
}
return count;
}
你正在迭代整個數組一次,所以我猜想它是O(N)。 – Blender
請修正你的符號。 'O(n)'和'o(n)'不是一回事。從某種意義上說,它們是對方的對立面。見http://en.wikipedia.org/wiki/Big_O_notation – NPE
我正在看代碼上面的例子:你是否試圖找到排序數組中所有重複項的出現次數? – jlordo