Topic describes

Ideas for solving problems (Mathematical laws)

  • Subject mainly from the two dimensional array of the elements of the lower left corner, constantly compare mobile, because the subject is given there is a 2 d array of features is that starting from ZuoXiaoJiao element, a list of the element, the element is always smaller than the following elements, a line element, the right of the element is always bigger than the left, this feature is our key to problem solving.

The problem solving code

var findNumberIn2DArray = function(matrix, target) {
    / /! If the number in the lower left corner is smaller than that in the lower left corner, move up one digit
    / /! If it is larger than the number in the lower left corner, move it one place to the right for comparison
    if (matrix.length === 0) return false;
    // if (matrix[0])
    // Navigate to the lower-left element
    let origin = matrix[matrix.length - 1] [0];
    // Define the pointer when moving;
    let top = matrix.length - 1;
    let right = 0;
    // Define the final result returned
    let res;
    while (1) {
        if (top < 0 || right === matrix[0].length) return false;
        origin = matrix[top][right];
        if (origin === target) return true;
        if (origin < target) {
            right++;
        }
        if(origin > target) { top--; }}};Copy the code

Conclusion (this topic gives us the enlightenment of thinking)

  • Lesson: Learn to solve problems by using the inherent rules in two-dimensional arrays.