Data structure---time complexity of job 1

This column is a summary column of my usual homework mistakes and where the knowledge is not solid.

1.Big O is an asymptotic notation, it will not express the exact number of times, the cpu operation speed is very fast, and it is meaningless to estimate it accurately.
2.This
insert image description here
function has a loop, but the loop is not executed n times, and i is incremented by 2 times each time, so the loop will only be executed log2(n) times.
3.This
insert image description here
function will be called recursively n - 1 times, each operation is one, so the time complexity is n
4.

insert image description here
In this topic, the array elements are in order , so the two numbers a and b can be searched from the beginning and the end respectively. According to whether the sum of the first and last elements is greater than sum, the search movement is determined. The entire array is searched once, and the result can be obtained , so the best time complexity is n
5.
insert image description here
T(n)

=T(n-1)+n

=T(n-2)+(n-1)+n

=T(n-3)+(n-2)+(n-1)+n

=T(0)+1+2+…+(n-2)+(n-1)+n

=1+1+2+…+(n-2)+(n-1)+n

As can be seen from the recursion formula, the value of the nth item needs to be recursed from n-1, and it has been recursed to 0 times, and a total of n-1 times has been recursed.

So the time complexity is n

6.Using
insert image description here
insert image description here
the three-time reversal method.
First time: reverse the elements of the entire array once.
Second time: reverse the sub-array
. Third time: reverse another sub-array

(1) Standard answer: Note that begin and end are the subscripts of the reversed array


void reverse(int* nums, int begin, int end)
{
    while (begin < end)
    {
        int tmp = nums[begin];
        nums[begin] = nums[end];
        nums[end] = tmp;

        ++begin;
        --end;
    }
}
void rotate(int* nums, int numsSize, int k) {
    if (k > numsSize)
    {
        k %= numsSize;
    }

    reverse(nums, 0, numsSize - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, numsSize - 1);
}

insert image description here
(2) My answer: begin and end both represent pointers

void reverse(int* begin, int* end ) {
	while (begin < end) {
		int temp = *begin;
		*begin = *end;
		*end = temp;
		begin++;
		end--;
	}

}
void rotate(int* arr,int sz, int k) {
	k = k % sz;

	reverse(arr, arr + sz - 1);
	reverse(arr, arr + k - 1);
	reverse(arr + k, arr + sz - 1);
}

insert image description here

Guess you like

Origin blog.csdn.net/qq_66238381/article/details/130171606