The sword refers to Offer04: the problem of finding C# interleaved array out of bounds in two-dimensional arrays

The sword refers to Offer04: Find C# in two-dimensional array and the problem of out-of-bounds interleaved array IndexOutOfRangeException

Array out of bounds exception
When submitting this topic, an error is reported:

Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array. Line 5: Solution.FindNumberIn2DArray(Int32[][] matrix, Int32 target) in Solution.cs Line 39: __Driver__.Main(String[] args) in __Driver__.cs


In int [][] martix={}the case of matrix[0].lengthan array out of bounds exception occurs. Because if there is an array martix={}, there is no matrix[0]such case, at which time the array subscript has been out of bounds.

Only if it is satisfied matrix.length=1can it be judged matrix[0].length==0(number of columns = 0)

So matrix[0]make sure that the array exists and the memory is allocated before performing the access operation.

public class Solution {
    
    
    public bool FindNumberIn2DArray(int[][] matrix, int target) {
    
    
        //左下角开始
        //行
        int row = matrix.Length-1;
        //列
        int col = 0;
        //如果是col<matrix[0].Length&&row>=0就会先执行数组下标访问导致越界
        while (row>=0&&col<matrix[0].Length)
        {
    
    
            int value = matrix[row][col];
            Console.WriteLine(value);
            if ( value== target)
            {
    
    
                return true;
            } 
            
            if (value > target)
            {
    
    
                row--;
                continue;
            }
            
            if (value < target)
            {
    
                    
                col++;
            }
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44394801/article/details/122204637