Big o 确定这部分代码的时间复杂度 //假设这两个数组是用户提供给我们的,我们不知道 //其内容 int A[5]={1,0,2,1,0};//(1) 操作 int y[5]={0,0,1,1,2};//(1) int n=5;//(1) 对于(int i=0;i

Big o 确定这部分代码的时间复杂度 //假设这两个数组是用户提供给我们的,我们不知道 //其内容 int A[5]={1,0,2,1,0};//(1) 操作 int y[5]={0,0,1,1,2};//(1) int n=5;//(1) 对于(int i=0;i,big-o,Big O,你可以这样计算: //Assume these 2 arrays were given to us by the user and we don't know // its contents int A[5] = {1,0,2,1,0}; // (1) operation int y[5] = {0,0,1,1,2}; // (1) int n = 5; // (1) for(int i=0; i<n; i++){ // (n) operations if(A[i]

你可以这样计算:

//Assume these 2 arrays were given to us by the user and we don't know 
// its contents
int A[5] = {1,0,2,1,0};   // (1) operation
int y[5] = {0,0,1,1,2};   // (1)

int n = 5; // (1)
for(int i=0; i<n; i++){   // (n) operations
    if(A[i]!= y[i]){      // is this (n) operations in worst case..?
        cout << "hello" << endl; // is this (n) operations in worst case?
    }
 }

你可以这样计算:

//Assume these 2 arrays were given to us by the user and we don't know 
// its contents
int A[5] = {1,0,2,1,0};   // (1) operation
int y[5] = {0,0,1,1,2};   // (1)

int n = 5; // (1)
for(int i=0; i<n; i++){   // (n) operations
    if(A[i]!= y[i]){      // is this (n) operations in worst case..?
        cout << "hello" << endl; // is this (n) operations in worst case?
    }
 }

不,它不是n^3。它可以是O(2*n)=O(n),但不是n^3。在最坏的情况下,我如何给出一个数字来量化if语句出现的次数。它仅仅是5次吗?不,它不是n^3。它可以是O(2*n)=O(n),但不是n^3在最坏的情况下,我如何给出一个数字来量化if语句出现的次数。它仅仅是5吗?
O(n)*(O(1) + O(1)) = O(2*n) = O(n)