The sword refers to Offer - lookup in a two-dimensional array

Topic description: In a two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.

Analysis: The stupid method is to convert the two-dimensional array into a one-dimensional array and then judge, but the performance is very poor, which is time-consuming and space-consuming. Carefully analyze the problem, the provided two-dimensional array is regular, each row increases from left to right, and each column increases from top to bottom, then, if the number at the end of a row is less than it, then the number of that row is less than it, a column If the number at the beginning is greater than it, then the number of that column is greater than it. We can start the comparison from the value in the upper right corner (lower left corner). If it is greater than it, the number of rows is reduced by one, if it is less than the number of columns is reduced by one.

code show as below:

private static bool Find(int[,] arr,int target)
        {
            bool found = false;
            if (arr == null)
                return found;
            int rows = arr.GetLength(0); //Number of rows in the two-dimensional array
            int cols = arr.GetLength(1); //The number of columns in the two-dimensional array
            int nowRow = 0; //current row
            int nowCol = cols-1; //current column
            while(nowRow<rows && nowCol>=0)
            {
                if (arr[nowRow, nowCol] == target)
                {
                    found = true;
                    break;
                }
                else if (arr[nowRow, nowCol] < target)
                    nowRow++;
                else
                    nowCol--;
            }
            return found;
        }
Summary: Be familiar with manipulating arrays.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326659464&siteId=291194637