[C language] Find elements in Young's matrix

Topic name:

Young's matrix

Topic content:

There is a matrix of numbers, each row of the matrix increases from left to right, and the matrix increases from bottom to top (the definition of Young's matrix), please write a program to find out whether a certain number exists in such a matrix.

A matrix like this is Young's matrix (essentially a two-dimensional array)

Require:

Time complexity is less than O(N)

Problem-solving ideas:

Because the problem requires that the time complexity is less than O(N), we cannot use violent enumeration traversal to solve this problem.

How to simplify the time complexity?

We first need to know where the specific simplification points are. O(N) is because we traverse one by one to exclude. In the worst case, we need to exclude n times, because we traverse once and exclude 1 . Then we have such a simplified idea, traversing once, can exclude multiple elements , so the time complexity must be less than O(N).

Thinking in this way, we found that the element in the upper right corner is very special .

Because it is the largest element in a row and the smallest element in a column.

If smaller than it, directly exclude the column.

If it is larger than that, the row is excluded directly .

And this method can continue to loop until the entire array is traversed

This is equivalent to traversing an element, which can exclude elements of a row/column, which greatly reduces the time complexity and meets the requirements of the topic.

TIP: How to customize the function to return two values?

We know that the return value of a function can only return one value, what if the title requires us to return two or more values?

At this time, we can use the parameters of the function , we pass the parameters, and pass the address of the parameter we need to return, so that we can return the parameters we want in the custom function!

source code:

int young_search(int arr[3][3], int row, int col, int k, int* x, int* y)
{
	int ret = 0;
	while (ret < row && col >= 0)
	{
		if (arr[ret][col - 1] == k)
		{
			*x = ret + 1;
			*y = col;
			return 1;
		}
		else if (arr[ret][col - 1] > k)
		{
			col--;
		}
		else
		{
			ret++;
		}
	}
	return 0;
}

int main()
{
	int arr[3][3] = { 1,2,3,4,5,6,7,8,9 };
	int k = 2;
	int x = 0;
	int y = 0;
	int ret = young_search(arr, 3, 3, k,&x,&y);
	if (ret == 1)
		printf("找到了,下标是%d,%d", x, y);
	else
		printf("找不到");
	return 0;
}

Guess you like

Origin blog.csdn.net/hanwangyyds/article/details/131770595