Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add solution for 74 - Search a 2D Matrix in C#1011

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Ahmad-A0 merged 2 commits intoneetcode-gh:mainfromritesh-dt:main
Sep 4, 2022
Merged
Changes fromall 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
47 changes: 47 additions & 0 deletionsc/74-Search-A-2D-Matrix.c
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
/*
Given a 2d matrix, where,
1. the rows are sorted from left to right,
2. the last element of each row is less than first element of next row

Find an efficient method to search for a given element in this array
Ex. matrix = [[ 1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]],
target = 3 -> true (3 exists)

The 2D matrix can be thought of as a 1D array if the rows are arranged
sequentially. And given the conditions, the 1D array will also be sorted.
So, binary search can be used to solve this problem with indexes (row, col)
rather than one.

Time: O(log(mn))
Space: O(1)
*/

bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target){
int m = matrixSize;
int n = *matrixColSize;

int low = 0;
int high = m*n - 1;

int mid = low + (high - low)/2;


while (low <= high) {
int row = mid / n;
int col = mid % n;

if (matrix[row][col] > target)
high = mid - 1;
else if (matrix[row][col] < target)
low = mid + 1;
else
return true;
mid = low + (high - low)/2;

}

return false;

}

[8]ページ先頭

©2009-2025 Movatter.jp