-
Notifications
You must be signed in to change notification settings - Fork 37
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
Ports - Ngoc #18
base: master
Are you sure you want to change the base?
Ports - Ngoc #18
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,8 +3,57 @@ | |
# If any number is found to be 0, the method updates all the numbers in the | ||
# corresponding row as well as the corresponding column to be 0. | ||
|
||
# Time complexity: ? | ||
# Space complexity: ? | ||
#Approach 1: | ||
# Time complexity: O(n^3) 3 nested loops | ||
# Space complexity: O(n^2) n is the number of rows and columns in the matrix being cloned | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is true if the number of rows and columns are the same (i.e. the input matrix is a "square" matrix). However, if you allow the number of rows & columns to differ, you probably need to specify |
||
|
||
def matrix_convert_to_zero_n_3(matrix) | ||
clone = matrix.map(&:dup) | ||
rows = matrix.length | ||
columns = matrix[0].length | ||
rows.times do |i| | ||
columns.times do |j| | ||
if matrix[i][j] == 0 | ||
columns.times do |jj| | ||
clone[i][jj] = 0 | ||
end | ||
rows.times do |ii| | ||
clone[ii][j] = 0 | ||
end | ||
end | ||
end | ||
end | ||
rows.times do |i| | ||
columns.times do |j| | ||
matrix[i][j] = clone[i][j] | ||
end | ||
end | ||
end | ||
|
||
#Approach 2: | ||
# Time complexity: O(n^2) 2 nested loops | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment as above ( |
||
# Space complexity: O(n) n is the number of affected rows and columns | ||
def matrix_convert_to_zero(matrix) | ||
raise NotImplementedError | ||
affected_rows = [] | ||
affected_columns = [] | ||
rows = matrix.length | ||
columns = matrix[0].length | ||
rows.times do |i| | ||
columns.times do |j| | ||
if matrix[i][j] == 0 | ||
affected_rows << i | ||
affected_columns << j | ||
end | ||
end | ||
end | ||
affected_rows.each do |i| | ||
columns.times do |j| | ||
matrix[i][j] = 0 | ||
end | ||
end | ||
affected_columns.each do |j| | ||
rows.times do |i| | ||
matrix[i][j] = 0 | ||
end | ||
end | ||
end |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep