Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Create Search-a-2D-Matrix-II.js #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 15, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions LeetcodeProblems/Search-a-2D-Matrix-II.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
https://leetcode.com/problems/search-a-2d-matrix-ii/description/
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[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.
*/

/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
if (matrix.length == 0)
return false
var lastCol = matrix[0].length - 1;
var firstRow = 0;

while(lastCol >= 0 && firstRow < matrix.length) {
if(matrix[firstRow][lastCol] == target) {
return true;
} else if(matrix[firstRow][lastCol] > target) {
lastCol--;
} else {
firstRow++;
}
}

return false;
};

const matrix1 = [
[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]
];

var main = function(n) {
console.log(searchMatrix(matrix1, 5));
console.log(searchMatrix(matrix1, 0));
console.log(searchMatrix(matrix1, 15));
}

module.exports.main = main;