This is the 16th day of my participation in the August Text Challenge.More challenges in August
The title
In an N by m 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. Perform an efficient function that takes such a two-dimensional array and an integer and determines whether the integer is in the array.
Source: LeetCode link: leetcode-cn.com/problems/er… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
My answer
/ * * *@param {number[][]} matrix
* @param {number} target
* @return {boolean}* /
var findNumberIn2DArray = function (matrix, target) {
if(matrix.length===0) {return false;
}
var i = 0;
var j = matrix[0].length - 1;
while(matrix[i][j] ! == target) {if (matrix[i][j] > target) {
j--;
} else if (matrix[i][j] < target) {
i++;
}
if(i>=matrix.length || j<0) {return false; }}return true;
};
Copy the code
If you go along with it, this is going to be a very difficult problem. If you want to find it quickly, you need to find as easy a path as possible. Comparing size to an element leads in only one direction. We notice that starting from the upper right (or lower left) corner of the two-dimensional array, we only have left down (or up to right) after comparing sizes. If it’s beyond the bounds of the data, it’s not.
The title
All numbers in an incrementally sorted array of length n-1 are unique, and each number is in the range 0 to n-1. Find one and only one of the n digits in the range 0 to n-1 that is not in the array.
Source: LeetCode link: leetcode-cn.com/problems/qu… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
My answer
/ * * *@param {number[]} nums
* @return {number}* /
var missingNumber = function (nums) {
return nums.length * (nums.length + 1) / 2 - nums.reduce((res, item) = > res + item, 0);
};
Copy the code
The easiest and most mindless way to do math is to subtract the sum of arrays from the sum of 1 to n minus 1.