[코테 풀이] Row With Maximum Ones

시내·2024년 6월 29일

Q_2643) Row With Maximum Ones

출처 : https://leetcode.com/problems/row-with-maximum-ones/

Given a m x n binary matrix mat, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row.

In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.

Return an array containing the index of the row, and the number of ones in it.

class Solution {
    public int[] rowAndMaximumOnes(int[][] mat) {
        List<int[]> onesInRow = new ArrayList<>();
        int ind = 0;
        for (int i = 0; i < mat.length; i++) {
            int counts = 0;
            for (int j = 0; j < mat[i].length; j++) {
                if (mat[i][j] == 1) counts++;
            }
            int[] sub = {i, counts};
            onesInRow.add(sub);
        }
        onesInRow.sort(new Comp());
        return onesInRow.get(0);
    }
    
    public class Comp implements Comparator<int[]> {
        @Override
        public int compare(int[] o1, int[] o2) {
            if (o1[1] == o2[1]) { //if counts are the same
                return o1[0] - o2[0]; //ascending (small row number)
            }
            return o2[1] - o1[1]; //counts descending
        }
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글