DEV Community

vc7
vc7

Posted on

1

LeetCode in Swift - 1072. Flip Columns For Maximum Number of Equal Rows

Problem

Data Structure

  • Hash map

Approach and the Routine

Base on the problem and the examples, a flip means, if there is a 0 will become 1 and if there is a 0 will become 1.

Normalize the rows

Because we only have to find the maximum number of all 0s and all 1s rows after a certain flipping of columns, which means we have to find the most appeared pattern.

01 -> 11 (Satisfied)
10 -> 00 (Satisfied)
Enter fullscreen mode Exit fullscreen mode

For example, after one flip of the column [0], we can get 2 rows are satisfied, so we can considering they are the same pattern.

01 -> 01
10 -> 01 (Normalized)
Enter fullscreen mode Exit fullscreen mode

To Count the appearance

We can use hash map to do the work, pattern as the key and count as the value.

// Routine 1st
01 -> [0, 1] -> [[0, 1]: 1]
10

// Routine 2st
01 
10 -> [0, 1] -> [[0, 1]: 2]
Enter fullscreen mode Exit fullscreen mode

Code

class Solution {
    func maxEqualRowsAfterFlips(_ matrix: [[Int]]) -> Int {
        // [pattern: count]
        var map = [[Int]: Int]()

        for row in matrix {
            let base = row[0]
            let pattern = row.map { $0 == base ? 0 : 1 }
            map[pattern, default: 0] += 1
        }

        return map.values.max() ?? 0
    }
}
Enter fullscreen mode Exit fullscreen mode

End of the post

That's it!

Please leave comment if you have any comments, thanks for your reading!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay