当前位置:网站首页>Finding JS in the two-dimensional array of sword fingers (clear version)

Finding JS in the two-dimensional array of sword fingers (clear version)

2022-06-09 04:58:00 Madrid Tianxin

In a n * m In a two-dimensional array , Each row is sorted in ascending order from left to right , Each column is sorted in ascending order from top to bottom . Please complete an efficient function , Enter such a two-dimensional array and an integer , Determine whether the array contains the integer .

Example :

The existing matrix matrix(5) as follows :

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
Given target = 5, return  true.

Given target = 20, return false.

My solution :

Say to violent problem solving no!!!!!!!!!!!!!! Traversal one by one takes up too much memory , And it is not the intention of this question .

The number of arrays is matrix.length, And the row is from the index 0 The line , So you have to subtract 1

First, let's start with the element in the lower left corner ----- That's ok =matrix.length-1 Column =0

If the target value > This value , Then move to the right , That is, column +1; If the target value < This value , Then move up , That is to say, yes -1.

If the target value = This value , Then return to true; If the array length is 0 Words , Indicates that there is no value , Then return to false;

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var findNumberIn2DArray = function (matrix, target) {
    let i = matrix.length - 1    // The value of the lower left row 
    let j = 0; // The first column value is 0
    if(matrix.length===0)return false
    while (i >= 0 && j <matrix[0].length) {
        if (target > matrix[i][j]) {
            j++;
        }
        else if (target < matrix[i][j]) {
            i--;
        }
        else if (target === matrix[i][j]) {
            return true
        }
       
    } 
     return false
};

原网站

版权声明
本文为[Madrid Tianxin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021438576018.html